We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find K Closest Elements

Number: 658

Difficulty: Medium

Paid? No

Companies: Meta, Yandex, DoorDash, Amazon, Google, Coupang, LinkedIn, Microsoft, Apple, Bloomberg, Adobe, TikTok, Uber, Yahoo


Problem Description

Given a sorted array of integers, our goal is to find k elements in the array that are closest to a target value x. If two numbers are equally close, the smaller element is preferred. The final answer should be returned in ascending order.


Key Insights

  • The input array is already sorted.
  • A binary search can be used to efficiently narrow down the potential starting position.
  • A two-pointers or sliding window approach is effective for selecting k consecutive elements.
  • The comparison of absolute differences (with a tie-breaker on values) is crucial.
  • Maintaining ascending order simplifies the final output.

Space and Time Complexity

Time Complexity: O(log n + k), where O(log n) for binary search and O(k) for collecting results. Space Complexity: O(k), for storing the output.


Solution

We can solve this problem by first using binary search to identify the left-most window where the k closest elements might start. The binary search operates over the possible starting indices for windows of size k (from 0 to n-k). For each middle index mid, we compare the distances between x and arr[mid] and arr[mid + k] to decide whether to move the window to the right or left. Once the correct starting position is found, return the k elements starting from that index. This approach leverages the sorted property of the array to efficiently converge on the optimal window.


Code Solutions

# Function to find k closest elements to x in a sorted array
def findClosestElements(arr, k, x):
    n = len(arr)
    # Initialize the binary search bounds for the starting index of the window
    left, right = 0, n - k
    # Binary search to find the best starting index
    while left < right:
        mid = left + (right - left) // 2
        # Compare the distance from x to arr[mid] and arr[mid+k]
        # If arr[mid] is farther from x than arr[mid+k], move window to the right
        if x - arr[mid] > arr[mid + k] - x:
            left = mid + 1
        else:
            # Otherwise, continue searching towards the left
            right = mid
    # Return the k elements starting from index `left`
    return arr[left:left + k]

# Example usage:
# arr = [1,2,3,4,5], k = 4, x = 3
# print(findClosestElements(arr, 4, 3))  # Output: [1,2,3,4]
← Back to All Questions