There exists an infinite number line, with its origin at 0 and extending towards the positive x-axis.
You are given a 2D array queries, which contains two types of queries:
For a query of type 1, queries[i] = [1, x]. Build an obstacle at distance x from the origin. It is guaranteed that there is no obstacle at distance x when the query is asked.
For a query of type 2, queries[i] = [2, x, sz]. Check if it is possible to place a block of size szanywhere in the range [0, x] on the line, such that the block entirely lies in the range [0, x]. A block cannot be placed if it intersects with any obstacle, but it may touch it. Note that you donot actually place the block. Queries are separate.
Return a boolean array results, where results[i] is true if you can place the block specified in the ith query of type 2, and false otherwise.
To efficiently insert obstacles and answer range queries, we maintain a sorted set of obstacle positions. For each type 2 query, we check all intervals between obstacles (including 0 and x as boundaries) to see if any interval can fit the block.
classSolution {
funblockPlacementQueries(queries: Array<IntArray>): List<Boolean> {
val obs = sortedSetOf<Int>()
val ans = mutableListOf<Boolean>()
for (q in queries) {
if (q[0] ==1) {
obs.add(q[1])
} else {
val x = q[1]
val sz = q[2]
obs.add(-1); obs.add(x+1)
var prev = -1var ok = falsefor (pos in obs.tailSet(0)) {
if (pos > x+1) breakif (pos - prev - 1>= sz) ok = true prev = pos
}
obs.remove(-1); obs.remove(x+1)
ans.add(ok)
}
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution:
defblockPlacementQueries(self, queries: list[list[int]]) -> list[bool]:
import bisect
obs = []
ans = []
for q in queries:
if q[0] ==1:
bisect.insort(obs, q[1])
else:
x, sz = q[1], q[2]
tmp = [0] + obs + [x+1]
tmp = [p for p in tmp if p <= x+1]
ok =Falsefor i in range(1, len(tmp)):
if tmp[i] - tmp[i-1] -1>= sz:
ok =Truebreak ans.append(ok)
return ans
impl Solution {
pubfnblock_placement_queries(queries: Vec<Vec<i32>>) -> Vec<bool> {
letmut obs =vec![];
letmut ans =vec![];
for q in queries {
if q[0] ==1 {
obs.push(q[1]);
obs.sort();
} else {
let x = q[1];
let sz = q[2];
letmut tmp =vec![0];
tmp.extend(&obs);
tmp.push(x+1);
tmp.retain(|&p| p <= x+1);
letmut ok =false;
for i in1..tmp.len() {
if tmp[i] - tmp[i-1] -1>= sz {
ok =true;
break;
}
}
ans.push(ok);
}
}
ans
}
}