Since the arrays are sorted, you can go through them with two pointers (one for each array). If |A[i+1] - B[j]| < |A[i] - B[j+1]| |A[i+1] - B[j]| < |A[i] - B[j+1]| , then the increment i , otherwise the increment j . Continue until you reach the end of one of the arrays. Keep track of minimum indexes as you move.
source share