Skip to content

visual walkthrough

Find K Closest Elements

MediumBinary Search on Window StartReported at: MetaGoogleAmazon+4

Binary search for the left edge of the best window.

Solve on LeetCode

The idea

The k closest values to x in a sorted array are always k neighbours in a row, so you only need to find where that window starts.

For a start mid, compare the window's first value with the value just after its end. Whichever is closer to x stays.

Complexity

approachtimespace
Sort by distanceO(n log n)O(n)
Binary search the window startO(log(n − k) + k)O(1)

More walkthroughs