#3161

Block Placement Queries

Hard
ArrayBinary SearchBinary Indexed TreeSegment TreeHash MapArray
LeetCode ↗

Approaches

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

Intuition

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

The optimal solution uses a data structure to efficiently manage obstacles and quickly determine if a block can be placed. By maintaining a sorted list of obstacles, we can use binary search to find the nearest obstacle and check placement conditions in logarithmic time.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a sorted list to store obstacles.
  2. 2Step 2: For each query, if it's type 1, insert the obstacle in sorted order.
  3. 3Step 3: For each query of type 2, use binary search to find the nearest obstacle within the range and check if the block can fit.
solution.py16 lines
1from bisect import insort, bisect_right
2
3def blockPlacementQueries(queries):
4    obstacles = []
5    results = []
6    for query in queries:
7        if query[0] == 1:
8            insort(obstacles, query[1])
9        elif query[0] == 2:
10            x, sz = query[1], query[2]
11            pos = bisect_right(obstacles, x)
12            canPlace = True
13            if pos > 0 and obstacles[pos - 1] >= x - sz:
14                canPlace = False
15            results.append(canPlace)
16    return results

Complexity note: The complexity is O(n log n) due to the insertion of obstacles into a sorted structure and the binary search for nearest obstacles, which is efficient for large inputs.

  • 1Using sorted data structures allows for efficient nearest obstacle queries.
  • 2Binary search can significantly reduce the time complexity of range queries.

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