K Closest Points to Origin
LeetCode 973 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू
Max-heap of size k on squared distance.
मैंने K Closest Points to Origin (LeetCode 973) ऐसे हल किया — Top K पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।
नीचे का विवरण अंग्रेज़ी में है।
Intuition
Keep only the k best candidates seen so far in a max-heap keyed by distance. A new point enters only if it's closer than the farthest point currently kept, which it then replaces.
Approach
- 1
Squared distance x² + y² (no square root needed).
- 2
Heap smaller than k → push.
- 3
Closer than the heap's farthest → pop it and push the new point.
- 4
The heap holds the answer.
मैंने कैसे हल किया
Max-heap of size kPythonO(n log k) time · O(k) space
import heapq
class Solution:
def kClosest(self, points, k):
pq = [] # max-heap via negative distance
for point in points:
x, y = point
distance = x ** 2 + y ** 2
if len(pq) < k:
heapq.heappush(pq, (-distance, point))
elif distance < -pq[0][0]:
heapq.heappop(pq)
heapq.heappush(pq, (-distance, point))
return [item[1] for item in pq]K Closest Points to Origin — अक्सर पूछे जाने वाले प्रश्न
K Closest Points to Origin के पीछे intuition क्या है?
Keep only the k best candidates seen so far in a max-heap keyed by distance. A new point enters only if it's closer than the farthest point currently kept, which it then replaces.
K Closest Points to Origin (LeetCode 973) कैसे हल करें?
1. Squared distance x² + y² (no square root needed). 2. Heap smaller than k → push. 3. Closer than the heap's farthest → pop it and push the new point. 4. The heap holds the answer.
K Closest Points to Origin की time और space complexity क्या है?
Time: O(n log k)। Space: O(k)। (Accepted approach: Max-heap of size k।)
K Closest Points to Origin में आम गलतियाँ क्या हैं?
Comparing squared distances avoids floating-point roots.