#3275

K-th Nearest Obstacle Queries

Medium
ArrayHeap (Priority Queue)Heap (Priority Queue)Sorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log k)
Space
O(n)
O(k)
💡

Intuition

Time O(n log k)Space O(k)

In the optimal approach, we use a max heap to maintain the k nearest obstacles efficiently. This allows us to quickly find the k-th nearest obstacle without sorting the entire list each time.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize a max heap to store the k smallest distances.
  2. 2Step 2: For each query, compute the distance from the origin and add it to the heap.
  3. 3Step 3: If the heap exceeds size k, remove the largest element (the root of the max heap).
  4. 4Step 4: After processing each query, if the heap has fewer than k elements, return -1; otherwise, return the root of the heap (the k-th nearest obstacle).
solution.py14 lines
1# Full working Python code
2import heapq
3from typing import List
4
5def kNearestObstacles(queries: List[List[int]], k: int) -> List[int]:
6    max_heap = []
7    results = []
8    for x, y in queries:
9        distance = abs(x) + abs(y)
10        heapq.heappush(max_heap, -distance)
11        if len(max_heap) > k:
12            heapq.heappop(max_heap)
13        results.append(-1 if len(max_heap) < k else -max_heap[0])
14    return results

Complexity note: The time complexity is O(n log k) because we perform log k operations for each of the n queries to maintain the max heap. The space complexity is O(k) for storing the k nearest distances in the heap.

  • 1Using a max heap allows us to efficiently track the k smallest distances without sorting the entire list.
  • 2The k-th nearest obstacle can only be determined once we have at least k obstacles.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.