↓Skip to main content
  1. LeetCode/

LeetCode 973: K Closest Points to Origin

·1 min· ·
LeetCode Medium Array Math Divide-and-Conquer Geometry
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: medium First Attempt: 2022-10-29

  • Submissions: Runtime Error → Accepted

Approach
#

For the k closest, keep a size-k heap whose top is the farthest so far (Heap Template 1). Python offers only a min-heap, so store -(x² + y²). Once full, heappushpop discards anything farther than the top. Compare squared distances; no square roots needed.

My Attempts
#

Attempt 1 used the old parameter name K (NameError); renaming it to k passed.

Solution
#

class Solution:
    def kClosest(self, points: List[List[int]], k: int) -> List[List[int]]:
        heap = []
        for x, y in points:
            item = (-(x * x + y * y), x, y)
            if len(heap) < k:
                heapq.heappush(heap, item)
            else:
                heapq.heappushpop(heap, item)
        return [[x, y] for _, x, y in heap]

Complexity
#

Time O(n log k), space O(k).

Mistakes to Avoid
#

  • To keep the closest, the top must be the farthest: store negated distances.
  • Squared distances suffice.

Interview Explanation
#

A size-k heap of negated squared distances keeps the farthest point on top; once full, each new point is pushpopped, leaving the k closest. Time O(n log k).

Related

LeetCode 105: Construct Binary Tree from Preorder and Inorder Traversal
·2 mins
LeetCode Medium Array Hash-Table Divide-and-Conquer Tree
LeetCode 105 note: the first pre-order value is the root, and its position in the in-order tells the left subtree’s size; look positions up in a dictionary for O(n)
LeetCode 215: Kth Largest Element in an Array
·2 mins
LeetCode Medium Array Divide-and-Conquer Sorting Heap-Priority-Queue
LeetCode 215 note: keep a min-heap of size k whose top is the k-th largest, or use quickselect for O(n) on average
LeetCode 347: Top K Frequent Elements
·1 min
LeetCode Medium Array Hash-Table Divide-and-Conquer Sorting
LeetCode 347 note: count first, then take the k most frequent with a size-k heap or a bucket sort indexed by count
LeetCode 1030: Matrix Cells in Distance Order
·2 mins
LeetCode Easy Array Math Geometry Sorting
LeetCode 1030 note: list every coordinate and sort by Manhattan distance to the center; return coordinates, not distances
LeetCode 892: Surface Area of 3D Shapes
·2 mins
LeetCode Easy Array Math Geometry Matrix
LeetCode 892 note: a stack of v cubes has 4v + 2 faces; subtract 2 × min for each overlap with the stacks above and to the left
LeetCode 883: Projection Area of 3D Shapes
·1 min
LeetCode Easy Array Math Geometry Matrix
LeetCode 883 note: the top view counts nonzero cells, and the front and side views sum each row’s and each column’s maximum