Magicsheet logo

Find K Closest Elements

Medium
30%
Updated 6/1/2025

Find K Closest Elements

What is this problem about?

The Find K Closest Elements interview question asks you to find the kk integers in a sorted array that are closest to a target value x. An integer aa is closer to xx than bb if ax<bx|a - x| < |b - x|, or if the absolute differences are equal and a<ba < b. The output must be sorted in ascending order.

Why is this asked in interviews?

This is a classic problem asked by Meta, Apple, and Microsoft. It tests your ability to leverage Sorted Array properties and optimize search space. While a simple sort by distance takes O(nlogn)O(n \log n), the array is already sorted, which hints at a more efficient O(logn+k)O(\log n + k) or O(log(nk))O(\log(n-k)) solution. It evaluations your mastery of Binary Search and Two Pointers patterns.

Algorithmic pattern used

There are two main approaches:

  1. Binary Search + Two Pointers (O(logn+k)O(\log n + k)): Find the closest position to xx using binary search. Use two pointers to expand outward, picking the closer of the two available neighbors until you have kk elements.
  2. Binary Search on Ranges (O(log(nk))O(\log(n-k))): Binary search for the start of the valid window. The comparison logic is: x - arr[mid] > arr[mid+k] - x. If true, the window must start further to the right.

Example explanation

arr = [1, 2, 3, 4, 5], k = 4, x = 3

  1. Initial window of size 4: [1, 2, 3, 4]. Start index 0.
  2. Next potential window: [2, 3, 4, 5]. Start index 1.
  3. Compare x - arr[0] (3-1=2) vs arr[0+4] - x (5-3=2). Since they are equal, we stay left (rule a<ba < b). Result: [1, 2, 3, 4].

Common mistakes candidates make

  • Sorting: Using Arrays.sort with a custom comparator, which is O(nlogn)O(n \log n) time and O(n)O(n) space.
  • Distance Ties: Not handling the ax==bx|a-x| == |b-x| case correctly by picking the smaller value.
  • Heap: Using a Max-Heap of size kk is O(nlogk)O(n \log k), which is better than sorting but still worse than binary search on a sorted array.

Interview preparation tip

When an array is already sorted, always aim for a solution involving Binary Search. If the problem asks for a range of elements, consider using binary search to find the boundaries of that range rather than finding individual elements.

Similar Questions