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.