Find K Closest Points to Origin

Last updated: April 5, 2025

Quick Overview

Given an array of points on a 2D plane, find the K closest points to the origin (0,0). Discuss trade-offs between sorting, heap, and quickselect approaches.

Canva
Coding & Algorithms
Software Engineer
Canva
April 5, 2025
Software Engineer
Unassisted Coding
Coding & Algorithms
Medium

8

4

4,234 solved


Given an array of points on a 2D plane, find the K closest points to the origin (0,0). Discuss trade-offs between sorting, heap, and quickselect approaches.

This question tests fundamental algorithm design and analysis skills. At Canva, spatial algorithms are relevant to the design editor (element proximity, snap-to-grid, collision detection). The interviewer wants to see clean code and thorough analysis of time/space complexity trade-offs.

What the Interviewer Expects
  • Implement at least two approaches with clear complexity analysis
  • Handle edge cases (k equals array length, duplicate distances, k=0)
  • Write clean, well-named code with proper function signatures
  • Discuss when each approach is preferred based on constraints
Key Topics to Cover
Heap data structures (min-heap, max-heap)
Quickselect algorithm
Time/space complexity analysis
Sorting algorithms
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • How would you modify this for a streaming input where points arrive continuously?
  • How would you extend this to find the K closest points to an arbitrary point, not just the origin?
  • What if the points are in 3D space instead of 2D?
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Problem Analysis

In this problem, we need to find the K closest points to the origin (0, 0) from a given list of points defined by their coordinates (x, y). The distance from the origin can be calculated using the Euc...

Approach
  1. Max-Heap Approach:
    • Initialize an empty max-heap.
    • Iterate through each point in the array:
      • Calculate the squared distance from the origin.
      • If the size of the heap is less...

Submit Your Answer
Markdown supported

Related Questions