Browse Curriculum
FAANGPrep Sprint
Medium

Find K Closest Elements

Find k closest integers to a given value x.

Problem Understanding

Given a sorted integer array arr, two integers k and x, return the k closest integers to x.

If |a - x| == |b - x|, the smaller number is chosen. The internal array must be sorted.

Example:

  • Input: arr = [1,2,3,4,5], k = 4, x = 3
  • Output: [1,2,3,4]

Algorithm Strategy

Approach 1: Max-Heap (Standard Top-K)
Similar to previous problems, maintain a Max-Heap of size K.

  • Priority is distance |val - x|.
  • Pop the element with the largest distance if size > K.

Approach 2: Two Pointers (Optimal for Sorted Input)
Since the array is sorted, the K closest elements will be a contiguous subarray.

  1. Use Binary Search to find the closest element to x.
  2. Expand Left and Right pointers to collect K neighbours.

Interactive Visualization

Step 1 / 1
Empty Heap

Initializing...

1x

Visualizing the selection process.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.