Tensorum
YouTubeशिकायला सुरुवात करा
LeetCode 973 · Top K

K Closest Points to Origin

LeetCode 973 · मध्यम · उपाय, intuition आणि टप्प्याटप्प्याने वॉकथ्रू

Max-heap of size k on squared distance.

मध्यमArrayMathDivide and ConquerGeometrySorting

मी 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. 1

    Squared distance x² + y² (no square root needed).

  2. 2

    Heap smaller than k → push.

  3. 3

    Closer than the heap's farthest → pop it and push the new point.

  4. 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.