AlgoMaster Logo

K Closest Points to Origin

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Naive Approach: Sorting

Intuition:

The most straightforward way to solve this problem is to calculate the distance of each point from the origin and then sort the points based on these distances.

Steps:

  1. Calculate the Euclidean distance for each point from the origin.
  2. Store the distances along with their respective points.
  3. Sort the points based on the calculated distances.
  4. Return the first K points from the sorted list.

Code:

2. Optimized Approach: Heap/Priority Queue

Intuition:

Instead of sorting the entire array, we can maintain a max heap of size K to keep track of the K closest points. This allows for more efficient insertion and removal operations as we process each point.

Steps:

  1. Create a max heap (priority queue) that will store the points based on their distance from the origin.
  2. Iterate through each point and calculate its distance from the origin.
  3. Maintain the heap to only contain the K closest points by removing the farthest point when the heap size exceeds K.
  4. Convert the result from the heap to an array and return it.

Code:

3. Optimal Approach: Quickselect

Intuition:

Quickselect is an optimization over quicksort that allows us to partition the array and only focus on the K closest elements. It can achieve an average time complexity better than sorting or using a heap.

Steps:

  1. Implement a partitioning method to organize points relative to a pivot such that all points closer than the pivot appear before all points farther than the pivot.
  2. Recursively adjust the partitioning based on the position of K relative to the pivot's final index until the partition yielding the closest K points is achieved.

Code: