Heap•Pattern: Max-Heap / Quickselect•Medium

Find K closest points to the origin

Problem Intuition & Objective

Return the K points nearest to (0,0) using Euclidean distance.

Time ComplexityO(n log k)
Optimal
Space ComplexityO(k)
Memory Bounds
Optimal Algorithmic Approach

Max-heap of size K: evict the farthest point when heap exceeds K.

Core Invariants & Edge Cases

  • Compare squared distances to avoid sqrt
  • Max-heap of size K: if new point closer than max, replace it
  • Alternatively quickselect for O(n) average
Previous ProblemKth largest element in a streamNext Problem Task scheduler — minimum CPU intervals with cooldown

System Design & Architecture Roadmap

Coding interviews are only 50% of the bar. Master High-Level Design, distributed systems, and Object-Oriented LLD.