MEDIUM NC#66 Heap / Priority Queue
973. K Closest Points to Origin
📖 Problem
Given an array of points where points[i] = [xi, yi], return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance. You may return the answer in any order. It is guaranteed that the answer exists and is unique.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Level-order traversal
- •Queue discipline
- •Shortest-step interpretation
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply BFS reasoning pattern
- •Apply Heap reasoning pattern
💡 Approach
- → Use max heap to maintain k closest points
- → Distance = x² + y² (no need to sqrt)
- → When heap size > k, remove farthest point
- → Time: O(n log k), Space: O(k)
🧭 Prerequisites
🛠️ Hints & Pitfalls
Hints
- •Use max heap to maintain k closest points
- •Distance = x² + y² (no need to sqrt)
- •When heap size > k, remove farthest point
Common Pitfalls
- •Time: O(n log k), Space: O(k)
🧪 Test Cases
Test Case 1
Not run Input:
kClosest([[1,3],[-2,2]], 1); Expected:
[[-2,2]] Test Case 2
Not run Input:
kClosest([[3,3],[5,-1],[-2,4]], 2); Expected:
[[5,-1], [-2,4]] Test Case 3
Not run Input:
kClosest(points: number[][], k: number); Expected:
Computed from hidden reference 📝 Code Editor
📤 Output