โ† Back to Index

๐Ÿ“š Find K Closest Elements โ€“ Java Cheat Sheet

๐Ÿ“Œ What Is It?

The Find K Closest Elements problem involves finding the K closest elements to a given target in a sorted array. The result should also be sorted in ascending order.

๐Ÿงฑ Pattern Template

class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        int left = 0, right = arr.length - k;

        while (left < right) {
            int mid = left + (right - left) / 2;

            if (x - arr[mid] > arr[mid + k] - x) {
                left = mid + 1; // Narrow down to the right half
            } else {
                right = mid; // Narrow down to the left half
            }
        }

        List<Integer> result = new ArrayList<>();
        for (int i = left; i < left + k; i++) {
            result.add(arr[i]);
        }

        return result;
    }
}

๐Ÿ“Š Time Complexity

โœ… Use Cases

๐Ÿ“˜ Common LeetCode Problems

๐Ÿงช Example: Find K Closest Elements

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

Explanation:
- The 4 closest elements to 3 are [1, 2, 3, 4].

๐Ÿ’ก Pro Tips