Heap pattern
Find K Closest Elements
Given a sorted array, a value k, and a target x, return the k elements closest to x as a sorted list. When two elements are equally close, prefer the smaller one. Watch it run step by step, then write your own pseudocode and get it checked by AI.
- LeetCode 658
- Medium
- 2 approaches
Sign in with Google or GitHub and you land straight on this page. DSA comes with the all labs plan and every ChaiCode batch.
HeapLeetCode 658
Medium
From the first idea to the best one
- 01 Brute force · sort by distance O(n log n)O(n) space
- 02 Optimized · size-k max-heap O(n log k)O(k) space
What you will learn
- How to read Find K Closest Elements and spot the heap pattern in it
- Brute force · sort by distance: O(n log n) time, O(n) space
- Optimized · size-k max-heap: O(n log k) time, O(k) space
- The pseudocode for each approach, its line lit as the animation runs
- Practice: write your own pseudocode and get it checked
More Heap
See Find K Closest Elements run, step by step
Sign in and this page opens on the animation, with all 7 Heap problems beside it.
DSA comes with the all labs plan and every ChaiCode batch.