Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the minimum difference between two arrays [closed]

Tags:

algorithm

Given two sorted arrays, A and B, find i,j for which |A[i] - B[j]| is minimum.

like image 988
simplfuzz Avatar asked Feb 26 '23 14:02

simplfuzz


1 Answers

Since the arrays are sorted, you can pass through them with 2 pointers (one for each array). If |A[i+1] - B[j]| < |A[i] - B[j+1]| then increment i, otherwise increment j. Continue until you've reached the end of one of the arrays. Keep track of the minimal indexes as you go.

like image 192
moinudin Avatar answered Mar 07 '23 15:03

moinudin