Given two arrays A and Q, foreach element of of Q, find the element in A with smallest difference
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
If you need, for every query value in Q, the element in A with the smallest absolute difference, the naive approach is easy but slow. The standard optimization is to sort A once and use binary search for each query, which turns repeated nearest-value lookups into an efficient and predictable routine.
The Naive Approach
The direct method checks every element of A for every value in Q.
This is fine for tiny inputs, but it costs O(len(A) * len(Q)), which becomes expensive when both arrays are large.
Sort Once, Then Binary Search
A faster method is:
- sort
A - for each query, find where it would be inserted
- compare the closest left and right neighbors
That reduces each query to O(log n) after the initial sort.
This is the standard efficient answer for many nearest-element lookup problems.
Why Binary Search Works Here
Once A is sorted, the closest value to x must be near the insertion point where x would fit in order. That means you do not need to scan the whole array. You only need to check at most two candidates:
- the neighbor just to the left
- the neighbor just to the right
That is the key observation that makes the algorithm fast.
Tie Handling Is a Design Choice
What if the query is equally close to two values?
For example, with A = [4, 8] and query 6, both choices are distance 2 away.
The code above uses this rule:
That means ties prefer the left neighbor. You can change the rule if your application prefers the larger value, the first-seen value, or even both candidates.
A Reusable Lookup Helper
If A stays fixed and you have many query batches, wrap the sorted array in a small helper object.
This avoids resorting A for every query set.
What About NumPy?
For large numeric workloads, NumPy can make the code more compact and often faster by vectorizing parts of the logic. The same idea still applies: sort the base array and use a search operation around the insertion points.
The algorithmic insight does not change. Vectorization just changes the implementation style.
Common Pitfalls
The biggest mistake is forgetting to sort A before using binary search. Without sorting, the insertion-point logic is meaningless.
Another issue is failing to handle boundary cases where the query falls before the first element or after the last element.
Developers also sometimes sort A repeatedly for every query batch, which throws away the performance benefit.
Finally, tie behavior should be explicit. If two values are equally close, choose a rule and document it so the output is predictable.
Summary
- The naive solution checks every value in
Afor every query inQ. - A faster solution sorts
Aonce and uses binary search for each query. - After sorting, the nearest value must be around the insertion point.
- Boundary handling and tie handling should be defined explicitly.
- If
Ais reused often, keep a sorted copy and query it repeatedly.
Related reading
- Given two arrays, find the permutations that give closest distance between two arrays
- Given two lines on a plane, how to find integer points closest to their intersection?
- Given two sequences, find the maximal overlap between ending of one and beginning of the other
- Go through all permutations of an array recursively
- Given two directory trees, how can I find out which files differ by content?
- Good algorithm and data structure for looking up words with missing letters?
- Gomoku array-based AI-algorithm?
- Good algorithm for combining items from N lists into one with balanced distribution?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.