Taro Logo

Block Placement Queries

#4 Most AskedHard
0 views
Topics:
ArraysGreedy Algorithms

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:

  1. 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.
  2. For a query of type 2, queries[i] = [2, x, sz]. Check if it is possible to place a block of size sz anywhere 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 do not 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.

Example 1:

Input: queries = [[1,2],[2,3,3],[2,3,1],[2,2,2]]

Output: [false,true,true]

Explanation:

For query 0, place an obstacle at x = 2. A block of size at most 2 can be placed before x = 3.

Example 2:

Input: queries = [[1,7],[2,7,6],[1,2],[2,7,5],[2,7,6]]

Output: [true,true,false]

Explanation:

  • Place an obstacle at x = 7 for query 0. A block of size at most 7 can be placed before x = 7.
  • Place an obstacle at x = 2 for query 2. Now, a block of size at most 5 can be placed before x = 7, and a block of size at most 2 before x = 2.

Constraints:

  • 1 <= queries.length <= 15 * 104
  • 2 <= queries[i].length <= 3
  • 1 <= queries[i][0] <= 2
  • 1 <= x, sz <= min(5 * 104, 3 * queries.length)
  • The input is generated such that for queries of type 1, no obstacle exists at distance x when the query is asked.
  • The input is generated such that there is at least one query of type 2.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What is the maximum coordinate range (or upper bound) of the linear line where obstacles can be placed?
  2. Are the obstacle coordinates guaranteed to be given in any specific order, or can they be placed arbitrarily along the line?
  3. When a query asks if a segment of length $sz$ can fit up to position $x$, does the available space need to lie entirely before $x$, or can it cross $x$?
  4. Can duplicate obstacle placement queries occur at the same coordinate, and how should overlapping obstacles be handled?
  5. What is the expected format of the query inputs and the corresponding boolean output collection (e.g., an array or a list of booleans)?

Brute Force Solution

Approach

Imagine you have a long straight road with some obstacles and you receive requests asking if you can place a block of a specific size before a certain point without hitting anything. The brute force approach looks at the exact stretch of road mentioned in each request and exhaustively checks every possible spot to see if the block fits.

Here's how the algorithm would work step-by-step:

  1. Read the first question or request about placing a block on the road.
  2. Look at the starting point of the road and the specific stopping point mentioned in the request.
  3. Check every single position along that allowed stretch of road, one by one, to see if an obstacle is already sitting there.
  4. For every potential spot, imagine placing the block of the requested size right there and verify whether any part of it overlaps with an existing obstacle or goes past the stopping point.
  5. If you find even one spot where the block fits completely within the allowed area without touching any obstacles, write down a positive answer for that request.
  6. If you check every single possible spot in the allowed stretch and the block simply cannot fit anywhere, write down a negative answer.
  7. Move on to the next request and repeat the entire checking process from the beginning until you have answered every single question.

Code Implementation

def solve_block_placement_queries(obstacles, queries):
    query_answers = []

    # Iterate through each query to independently evaluate if a block can be placed
    for current_query in queries:
        if current_query[0] == 1:
            obstacle_position = current_query[1]
            obstacles.append(obstacle_position)
            obstacles.sort()
        else:
            stopping_limit = current_query[1]
            block_size = current_query[2]
            is_block_placed = False

            # Check every possible starting coordinate from the beginning of the road
            for start_coordinate in range(stopping_limit - block_size + 1):
                end_coordinate = start_coordinate + block_size
                has_obstacle_overlap = False

                for current_obstacle in obstacles:
                    if start_coordinate <= current_obstacle < end_coordinate:
                        has_obstacle_overlap = True
                        break

                # Stop searching early once we find a valid position that fits the block
                if not has_obstacle_overlap:
                    is_block_placed = True
                    break

            query_answers.append(is_block_placed)

    # Return the collected boolean answers for all the block placement queries
    return query_answers

Big(O) Analysis

Time Complexity
O(Q * X) – For each of the Q queries, we examine a stretch of the road up to a stopping point X by exhaustively checking every single position one by one. In the worst case, each query might require checking up to X potential starting spots along the road to see if a block of the requested size fits without hitting an obstacle. Summing this up across all Q requests yields approximately Q * X operations, which simplifies to O(Q * X).
Space Complexity
O(1) – The brute force approach processes each request on the fly by checking individual positions along the road without utilizing any auxiliary data structures that scale with the input size N. We only allocate a few primitive variables for loop counters and boundary checks, meaning the extra memory remains constant. As the number of obstacles and requests grows, the algorithm requires no additional dynamic memory storage beyond the given inputs.

Optimal Solution

Approach

To efficiently answer whether a block of a certain size can fit into available empty spaces, we can think of the problem in terms of distances between obstacles. By grouping these distances and using a smart searching technique, we can quickly determine if any gap is large enough to hold the requested block.

Here's how the algorithm would work step-by-step:

  1. First, map out all the fixed obstacles along our path to understand the sizes of the empty gaps between them.
  2. Calculate the size of each empty gap and keep track of the largest gap we have seen up to any given point along the path.
  3. When a question asks if a block of a certain size can fit before a specific position, look at the largest gap available in that region.
  4. If the requested block size is smaller than or equal to that largest available gap, we know for sure it can fit.
  5. If it is too large, check if the remaining space at the very beginning of the path before the first obstacle is large enough to hold the block.
  6. By relying on our pre-calculated maximum gaps, we can instantly answer every question without having to scan through all the obstacles one by one.

Code Implementation

def get_block_placement_results(obstacle_positions, placement_queries):
    sorted_obstacles = sorted(obstacle_positions)
    
    # We precompute gaps to avoid repeatedly scanning obstacles for every query.
    max_gap_to_position = [0] * len(sorted_obstacles)
    
    max_gap_to_position[0] = sorted_obstacles[0]
    
    for obstacle_index in range(1, len(sorted_obstacles)):
        current_gap = sorted_obstacles[obstacle_index] - sorted_obstacles[obstacle_index - 1]
        max_gap_to_position[obstacle_index] = max(max_gap_to_position[obstacle_index - 1], current_gap)
        
    query_results = []
    
    for query_limit, required_size in placement_queries:
        valid_obstacle_count = 0
        
        # Binary search helps efficiently locate the relevant obstacles before the limit.
        low_index = 0
        high_index = len(sorted_obstacles) - 1
        target_index = -1
        
        while low_index <= high_index:
            mid_index = (low_index + high_index) // 2
            if sorted_obstacles[mid_index] < query_limit:
                target_index = mid_index
                low_index = mid_index + 1
            else:
                high_index = mid_index - 1
                
        if target_index == -1:
            can_fit = sorted_obstacles[0] >= required_size
        else:
            largest_gap_seen = max_gap_to_position[target_index]
            initial_gap = sorted_obstacles[0]
            can_fit = (largest_gap_seen >= required_size) or (initial_gap >= required_size and query_limit > sorted_obstacles[target_index] + required_size)
            
        query_results.append(can_fit)
        
    # Returning the boolean list gives immediate answers for all evaluated queries.
    return query_results

Big(O) Analysis

Time Complexity
O(n log n) – Mapping out the obstacles and calculating the sizes of the empty gaps takes linear time proportional to the number of obstacles n. Organizing these gap sizes and maximum prefix bounds for efficient searching typically requires sorting or a segment tree structure, which introduces a logarithmic factor. Answering each of the query operations then takes logarithmic time using binary search. This leads to approximately n log n operations for the preprocessing phase combined with log n per query, which simplifies overall to O(n log n).
Space Complexity
O(N) – To satisfy the requirements of mapping obstacles and pre-calculating the largest gaps up to any given point, the algorithm utilizes auxiliary data structures such as a Segment Tree or an ordered list whose sizes scale directly with the number of obstacles, denoted as N. Specifically, storing the gap sizes and the pre-calculated maximum prefix gaps requires additional arrays or tree nodes proportional to N. Temporary variables used during the building and querying phases consume a constant amount of extra space. Therefore, the total auxiliary space complexity is driven by these data structures and simplifies to Big O of N.

Edge Cases

Querying for a block size larger than the maximum coordinate limit
How to Handle:
The segment check naturally returns false because no gap can exceed the coordinate boundary.
Queries requesting placement or checks at coordinate zero
How to Handle:
Segment tree or Fenwick tree indices must be offset or 1-indexed to safely handle zero coordinates without out-of-bounds errors.
Maximum possible coordinate values approaching the upper constraints
How to Handle:
Coordinate compression or sparse segment tree implementations must be used to prevent memory limit exceed errors.
Consecutive duplicate obstacle insertions at the same coordinate
How to Handle:
The data structure should ignore redundant insertions to maintain accurate contiguous gap measurements.
A query asking for a block size of one
How to Handle:
The algorithm successfully validates it as long as there is at least one unit of free space before the query limit.
No obstacles placed yet when the first existence query is executed
How to Handle:
The structure must treat the entire range up to the query limit as a single contiguous free space.
Interleaved placement and query operations covering the entire coordinate line
How to Handle:
Using an ordered set combined with a segment tree ensures logarithmic time complexity per operation for efficient scaling.
Very large coordinate values causing potential integer overflow in segment calculations
How to Handle:
64-bit integer types must be used for all coordinate math and distance comparisons to prevent overflow bugs.
0/9 completed