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
LeetCode-এ খুলুন ↗

আমি 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.