Find K Closest Elements — LeetCode 658 Python Solution
MediumArrayTwo PointersBinary SearchSortingSliding WindowHeap (Priority Queue)
- Problem
- #658
- Pattern
- Sliding Window
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n) (after optional sort O(n log n)) |
| Space | O(1) auxiliary |
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
LeetCode 786K-th Smallest Prime FractionMediumLeetCode 475HeatersMediumLeetCode 719Find K-th Smallest Pair DistanceHardLeetCode 825Friends Of Appropriate AgesMediumLeetCode 1385Find the Distance Value Between Two ArraysEasyLeetCode 1498Number of Subsequences That Satisfy the Given Sum ConditionMedium
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.