MediumNo. 0658
Find K Closest Elements — LeetCode 658 Python Solution
- Pattern
- Sliding Window
- Topics
- Array, Two Pointers, Binary Search, Sorting, Sliding Window, Heap (Priority Queue)
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array. The result should also be sorted in ascending order.
Python solution
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])Complexity
- Time
- O(n) (after optional sort O(n log n))
- Space · auxiliary
- O(1)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 658. Find K Closest Elements is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0786 | K-th Smallest Prime Fraction | Medium |
| 0475 | Heaters | Medium |
| 0719 | Find K-th Smallest Pair Distance | Hard |
| 0825 | Friends Of Appropriate Ages | Medium |
| 1385 | Find the Distance Value Between Two Arrays | Easy |
| 1498 | Number of Subsequences That Satisfy the Given Sum Condition | Medium |
Frequently asked questions
- How hard is LeetCode 658. Find K Closest Elements?
LeetCode 658. Find K Closest Elements is rated Medium on LeetCode.
- What is the time complexity of LeetCode 658. Find K Closest Elements?
The Python solution on this page runs in O(n) (after optional sort O(n log n)).
- What is the space complexity of LeetCode 658. Find K Closest Elements?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 658. Find K Closest Elements cover?
LeetCode 658. Find K Closest Elements is tagged Array, Two Pointers, Binary Search, Sorting, Sliding Window and Heap (Priority Queue) on LeetCode.