Block Placement Queries - Problem
Imagine you're managing a construction site on an infinite number line that starts at position 0 and extends infinitely to the right. You need to handle two types of operations:
- Type 1: Place Obstacle -
[1, x]means you build a permanent obstacle at position x - Type 2: Block Placement Query -
[2, x, sz]asks whether you can place a block of size sz anywhere in the range[0, x]
The key constraints are:
- A block of size sz occupies positions
[start, start + sz] - The entire block must fit within
[0, x] - The block cannot intersect with any obstacle, but it can touch obstacles at the endpoints
- You don't actually place the block - you just check if it's possible
Goal: Return a boolean array where each entry corresponds to whether a Type 2 query is feasible.
Input & Output
example_1.py โ Basic Operations
$
Input:
queries = [[1,2],[2,3,1],[2,1,1]]
โบ
Output:
[true, true]
๐ก Note:
First, place obstacle at position 2. Then check if we can place block of size 1 in [0,3] - yes, we can place it at [0,1] or [1,2]. Finally, check if we can place block of size 1 in [0,1] - yes, at [0,1].
example_2.py โ No Space Available
$
Input:
queries = [[1,0],[1,1],[2,1,2]]
โบ
Output:
[false]
๐ก Note:
Place obstacles at positions 0 and 1. Then try to place block of size 2 in [0,1] - impossible because obstacles occupy the entire range.
example_3.py โ Multiple Queries
$
Input:
queries = [[2,5,2],[1,3],[2,5,2],[1,1],[2,5,2]]
โบ
Output:
[true, true, false]
๐ก Note:
Initially no obstacles, so block of size 2 fits in [0,5]. After adding obstacle at 3, block still fits (e.g., at [0,2]). After adding obstacle at 1, largest gap is only size 1, so block of size 2 won't fit.
Visualization
Tap to expand
Understanding the Visualization
1
Site Survey
Maintain a sorted list of all existing structures (obstacles) on the construction line
2
Gap Analysis
For each equipment request, identify all available gaps between structures within the specified range
3
Size Validation
Check if any gap is large enough to accommodate the requested equipment block
4
Placement Decision
Return whether placement is possible without actually placing the equipment
Key Takeaway
๐ฏ Key Insight: Instead of checking every position, we maintain obstacles in sorted order and use binary search to efficiently find gaps. We only need to verify if the largest available gap can accommodate our block size.
Time & Space Complexity
Time Complexity
O(Q ร N log N)
Q queries, each requiring O(N log N) for binary search and gap checking
โก Linearithmic
Space Complexity
O(N)
Store obstacles in sorted order
โ Linear Space
Constraints
- 1 โค queries.length โค 15 ร 104
- For type 1: queries[i] = [1, xi] where 0 โค xi โค 5 ร 104
- For type 2: queries[i] = [2, xi, szi] where 0 โค xi, szi โค 5 ร 104
- No duplicate obstacles at the same position when type 1 queries are made
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code