Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
There is an infinite 2D plane.
You are given a positive integer k. You are also given a 2D array queries, which contains the following queries:
queries[i] = [x, y]: Build an obstacle at coordinate (x, y) in the plane. It is guaranteed that there is no obstacle at this coordinate when this query is made.After each query, you need to find the distance of the kth nearest obstacle from the origin.
Return an integer array results where results[i] denotes the kth nearest obstacle after query i, or results[i] == -1 if there are less than k obstacles.
Note that initially there are no obstacles anywhere.
The distance of an obstacle at coordinate (x, y) from the origin is given by |x| + |y|.
Example 1:
Input: queries = [[1,2],[3,4],[2,3],[-3,0]], k = 2
Output: [-1,7,5,3]
Explanation:
queries[0], there are less than 2 obstacles.queries[1], there are obstacles at distances 3 and 7.queries[2], there are obstacles at distances 3, 5, and 7.queries[3], there are obstacles at distances 3, 3, 5, and 7.Example 2:
Input: queries = [[5,5],[4,4],[3,3]], k = 1
Output: [10,8,6]
Explanation:
queries[0], there is an obstacle at distance 10.queries[1], there are obstacles at distances 8 and 10.queries[2], there are obstacles at distances 6, 8, and 10.Constraints:
1 <= queries.length <= 2 * 105queries[i] are unique.-109 <= queries[i][0], queries[i][1] <= 1091 <= k <= 105Problem summary: There is an infinite 2D plane. You are given a positive integer k. You are also given a 2D array queries, which contains the following queries: queries[i] = [x, y]: Build an obstacle at coordinate (x, y) in the plane. It is guaranteed that there is no obstacle at this coordinate when this query is made. After each query, you need to find the distance of the kth nearest obstacle from the origin. Return an integer array results where results[i] denotes the kth nearest obstacle after query i, or results[i] == -1 if there are less than k obstacles. Note that initially there are no obstacles anywhere. The distance of an obstacle at coordinate (x, y) from the origin is given by |x| + |y|.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array
[[1,2],[3,4],[2,3],[-3,0]] 2
[[5,5],[4,4],[3,3]] 1
k-closest-points-to-origin)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #3275: K-th Nearest Obstacle Queries
class Solution {
public int[] resultsArray(int[][] queries, int k) {
int n = queries.length;
int[] ans = new int[n];
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
for (int i = 0; i < n; ++i) {
int x = Math.abs(queries[i][0]) + Math.abs(queries[i][1]);
pq.offer(x);
if (i >= k) {
pq.poll();
}
ans[i] = i >= k - 1 ? pq.peek() : -1;
}
return ans;
}
}
// Accepted solution for LeetCode #3275: K-th Nearest Obstacle Queries
func resultsArray(queries [][]int, k int) (ans []int) {
pq := &hp{}
for _, q := range queries {
x := abs(q[0]) + abs(q[1])
pq.push(x)
if pq.Len() > k {
pq.pop()
}
if pq.Len() == k {
ans = append(ans, pq.IntSlice[0])
} else {
ans = append(ans, -1)
}
}
return
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
type hp struct{ sort.IntSlice }
func (h hp) Less(i, j int) bool { return h.IntSlice[i] > h.IntSlice[j] }
func (h *hp) Push(v any) { h.IntSlice = append(h.IntSlice, v.(int)) }
func (h *hp) Pop() any {
a := h.IntSlice
v := a[len(a)-1]
h.IntSlice = a[:len(a)-1]
return v
}
func (h *hp) push(v int) { heap.Push(h, v) }
func (h *hp) pop() int { return heap.Pop(h).(int) }
# Accepted solution for LeetCode #3275: K-th Nearest Obstacle Queries
class Solution:
def resultsArray(self, queries: List[List[int]], k: int) -> List[int]:
ans = []
pq = []
for i, (x, y) in enumerate(queries):
heappush(pq, -(abs(x) + abs(y)))
if i >= k:
heappop(pq)
ans.append(-pq[0] if i >= k - 1 else -1)
return ans
// Accepted solution for LeetCode #3275: K-th Nearest Obstacle Queries
// Rust example auto-generated from java reference.
// Replace the signature and local types with the exact LeetCode harness for this problem.
impl Solution {
pub fn rust_example() {
// Port the logic from the reference block below.
}
}
// Reference (java):
// // Accepted solution for LeetCode #3275: K-th Nearest Obstacle Queries
// class Solution {
// public int[] resultsArray(int[][] queries, int k) {
// int n = queries.length;
// int[] ans = new int[n];
// PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
// for (int i = 0; i < n; ++i) {
// int x = Math.abs(queries[i][0]) + Math.abs(queries[i][1]);
// pq.offer(x);
// if (i >= k) {
// pq.poll();
// }
// ans[i] = i >= k - 1 ? pq.peek() : -1;
// }
// return ans;
// }
// }
// Accepted solution for LeetCode #3275: K-th Nearest Obstacle Queries
function resultsArray(queries: number[][], k: number): number[] {
const pq = new MaxPriorityQueue<number>();
const ans: number[] = [];
for (const [x, y] of queries) {
pq.enqueue(Math.abs(x) + Math.abs(y));
if (pq.size() > k) {
pq.dequeue();
}
ans.push(pq.size() === k ? pq.front() : -1);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair or subarray. The outer loop fixes a starting point, the inner loop extends or searches. For n elements this gives up to n²/2 operations. No extra space, but the quadratic time is prohibitive for large inputs.
Most array problems have an O(n²) brute force (nested loops) and an O(n) optimal (single pass with clever state tracking). The key is identifying what information to maintain as you scan: a running max, a prefix sum, a hash map of seen values, or two pointers.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.