Find K Closest Elements — LeetCode 658 Python Solution

MediumArrayTwo PointersBinary SearchSortingSliding WindowHeap (Priority Queue)
Problem
#658
Reading time
2 min

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

MeasureComplexity
TimeO(n) (after optional sort O(n log n))
SpaceO(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

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview