Find the minimum difference between two arrays

For two sorted arrays A and B, find i, j for which | A [i] - B [j] | minimally.

+4
source share
1 answer

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.

+8
source

All Articles