Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: K Closest Points to Origin

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "973" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0). The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 - y2)2). You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in). Example 1: Input: points = [[1,3],[-2,2]], k = 1 Output: [[-2,2]] Explanation: The distance between (1, 3) and the origin is sqrt(10). The distance between (-2, 2) and the origin is sqrt(8). Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin. We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]]. Example 2: Input: points = [[3,3],[5,-1],[-2,4]], k = 2 Output: [[3,3],[-2,4]] Explanation: The answer [[-2,4],[3,3]] would also be accepted. Constraints: 1 <= k <= points.length <= 104 -104 <= xi, yi <= 104

Explanation

Here's a solution to find the k closest points to the origin, along with an explanation:

  • Key Approach: Use a max-heap (priority queue) of size k to store the k closest points encountered so far. For each point, calculate its squared distance to the origin. If the heap is not yet full (size < k), add the point and its distance to the heap. If the heap is full and the current point's distance is less than the largest distance in the heap (heap's root), remove the root and add the current point to the heap. The squared distance is used to avoid the expensive square root operation, as it doesn't affect the comparison.
  • Heap Maintenance: The max-heap ensures that the root always contains the point with the largest distance among the k closest points found so far.
  • Final Result: Once all points have been processed, the heap contains the k closest points. Extract these points from the heap to form the result.

  • Complexity:

    • Runtime: O(n log k), where n is the number of points.
    • Storage: O(k)

Code

    import heapq

def k_closest(points, k):
    """
    Finds the k closest points to the origin (0, 0).

    Args:
        points: A list of points, where each point is a list [x, y].
        k: The number of closest points to return.

    Returns:
        A list of the k closest points to the origin.
    """

    max_heap = []  # Use a max-heap to store the k closest points
    for point in points:
        x, y = point
        dist_sq = x**2 + y**2  # Calculate squared distance to origin

        if len(max_heap) < k:
            heapq.heappush(max_heap, (-dist_sq, point))  # Negate distance for max-heap
        else:
            if dist_sq < -max_heap[0][0]:
                heapq.heappop(max_heap)
                heapq.heappush(max_heap, (-dist_sq, point))

    result = [point for _, point in max_heap]  # Extract points from heap
    return result

More from this blog

C

Chatmagic blog

2894 posts