LeetCode Problem Workspace

Find K Closest Elements

Identify the k integers closest to a target x in a sorted array using binary search and two-pointer strategies efficiently.

category

6

Topics

code_blocks

6

Code langs

hub

3

Related

Practice Focus

Medium · Binary search over the valid answer space

bolt

Answer-first summary

Identify the k integers closest to a target x in a sorted array using binary search and two-pointer strategies efficiently.

Interview AiBox logo

Ace coding interviews with Interview AiBox guidance for Binary search over the valid answer space

Try AiBox Copilotarrow_forward

This problem requires returning the k integers in arr nearest to a given value x, maintaining ascending order. The optimal approach uses binary search over the potential window of answers combined with two-pointer adjustments to ensure the closest elements are selected. Attention to edge cases like ties and array boundaries is crucial for correct implementation.

Problem Statement

You are given a sorted integer array arr and two integers k and x. Your task is to find the k integers in arr that are closest to x and return them sorted in ascending order. If two numbers are equally close to x, the smaller number should appear first.

Formally, an integer a is closer to x than an integer b if |a - x| < |b - x|, or if |a - x| == |b - x| and a < b. Ensure your solution handles arrays with duplicates, edge boundaries, and maintains the final sorted order for the selected elements.

Examples

Example 1

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

Output: [1,2,3,4]

Example details omitted.

Example 2

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

Output: [1,1,2,3]

Example details omitted.

Constraints

  • 1 <= k <= arr.length
  • 1 <= arr.length <= 104
  • arr is sorted in ascending order.
  • -104 <= arr[i], x <= 104

Solution Approach

Binary Search Over Answer Window

Use binary search to locate the left boundary of a window of size k where the elements are closest to x. Adjust the window by comparing distances at the edges, moving left or right to minimize |arr[i] - x|. This ensures O(log(n-k) + k) time complexity and efficiently narrows the candidate range.

Two-Pointer Expansion

After identifying an approximate position near x, use two pointers extending left and right to select k closest elements. Compare the distance of elements at both pointers to x and include the closer element. Continue until k elements are collected, preserving order and handling tie-breakers correctly.

Heap-Based Approach

Push each element with its distance to x into a min-heap or max-heap depending on sorting preference. Pop k elements with minimal distances, then sort them ascendingly. While simpler to implement, this method may use O(n + k log k) time and O(n) space, making it less efficient for large arrays compared to binary search.

Complexity Analysis

Metric Value
Time Depends on the final approach
Space Depends on the final approach

Binary search with two pointers yields O(log(n-k) + k) time and O(1) extra space. Heap-based solutions take O(n + k log k) time and O(n) space. The trade-off is between execution speed and code simplicity for different input sizes.

What Interviewers Usually Probe

  • Expect discussion on edge handling when x is outside arr's range.
  • Ask about tie-breaking rules for elements equidistant to x.
  • Probe understanding of binary search on the answer space versus linear scanning.

Common Pitfalls or Variants

Common pitfalls

  • Forgetting to sort the final k elements before returning.
  • Mismanaging tie-breakers when two numbers are equally close to x.
  • Using linear search which exceeds time limits on large arrays.

Follow-up variants

  • Finding k closest elements in an unsorted array requiring O(n log n) sorting.
  • Returning k farthest elements instead of closest using the same patterns.
  • Handling streaming data where arr is dynamic and nearest neighbors must update.

FAQ

What is the most efficient pattern for solving Find K Closest Elements?

Binary search over the potential window combined with two-pointer selection is the optimal approach, avoiding linear scanning of the entire array.

How should ties be handled when two elements are equally close to x?

Always prefer the smaller element first to maintain ascending order in the final result.

Can this problem be solved with a heap?

Yes, using a min-heap based on distance to x works, but it increases space usage and is less efficient than the binary search approach.

What are common mistakes when implementing two-pointer selection?

Incorrectly expanding pointers beyond array bounds or ignoring tie-break rules leads to wrong results.

Does the array need to be sorted before applying binary search?

Yes, the binary search window approach relies on the array being sorted in ascending order.

terminal

Solution

Solution 1: Sort

#### Python3

1
2
3
4
class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        arr.sort(key=lambda v: abs(v - x))
        return sorted(arr[:k])

Solution 2: Binary search

#### Python3

1
2
3
4
class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        arr.sort(key=lambda v: abs(v - x))
        return sorted(arr[:k])

Solution 3

#### Python3

1
2
3
4
class Solution:
    def findClosestElements(self, arr: List[int], k: int, x: int) -> List[int]:
        arr.sort(key=lambda v: abs(v - x))
        return sorted(arr[:k])
Find K Closest Elements Solution: Binary search over the valid answer s… | LeetCode #658 Medium