#658
Find K Closest Elements
MediumArrayTwo PointersBinary SearchSliding WindowSortingHeap (Priority Queue)Two PointersBinary SearchSorting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n log n) | O(n) |
| Space | O(n) | O(1) |
💡
Intuition
Time O(n)Space O(1)
Using a two-pointer approach allows us to efficiently find the k closest elements without sorting the entire array. This method leverages the fact that the array is already sorted, making it faster and more space-efficient.
⚙️
Algorithm
3 steps- 1Step 1: Use binary search to find the closest index to x.
- 2Step 2: Initialize two pointers, one to the left and one to the right of the found index.
- 3Step 3: Expand the pointers outward until k elements are collected, choosing the closer element at each step.
solution.py8 lines
1def findClosestElements(arr, k, x):
2 left, right = 0, len(arr) - 1
3 while right - left >= k:
4 if abs(arr[left] - x) <= abs(arr[right] - x):
5 right -= 1
6 else:
7 left += 1
8 return arr[left:left + k]ℹ
Complexity note: The time complexity is O(n) in the worst case for the two-pointer approach, and the space complexity is O(1) since we are using pointers instead of additional data structures.
- 1The array is sorted, which allows for efficient searching and selection.
- 2Using two pointers can significantly reduce the time complexity compared to sorting.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.