Problem Description
Given an infinite 2D plane and a series of queries that add obstacles at specified coordinates, we must return the Manhattan distance of the k-th nearest obstacle from the origin after each query. The Manhattan distance of a point (x, y) is defined as |x| + |y|. If there are fewer than k obstacles at any point, output -1 for that query.
Key Insights
- We need to efficiently maintain the k smallest Manhattan distances seen so far.
- A max-heap of size k is an ideal data structure since its root always contains the current k-th smallest (or the highest among the k smallest) Manhattan distance.
- For each query:
- Compute the Manhattan distance.
- If the heap has fewer than k elements, simply add the new distance.
- Otherwise, if the new distance is smaller than the maximum (root) of the heap, remove the current maximum and insert the new distance.
- The root of the heap is the k-th nearest obstacle when the heap size is at least k.
Space and Time Complexity
Time Complexity: O(Q * log k) where Q is the number of queries, since each query does at most O(log k) operations. Space Complexity: O(k) for maintaining the max-heap.
Solution
The approach uses a max-heap (simulated with a min-heap by storing negative values in languages that provide only a min-heap by default like Python) to maintain the k smallest Manhattan distances. For each query, we:
- Calculate the Manhattan distance = |x| + |y|.
- If the current number of obstacles is less than k, we push the negative of the distance onto the heap.
- Otherwise, check if the new distance is smaller than the current k-th smallest (i.e., if it is smaller than -heap[0]). If so, pop the maximum and push the new distance.
- Append the current k-th smallest to the results if we have k obstacles; else append -1.
This guarantees that the k-th nearest obstacle is available in the heap’s root after processing each query.