Taro Logo

Maximum Walls Destroyed by Robots

#12 Most AskedHard
0 views
Topics:
ArraysBinary SearchGreedy Algorithms
There is an endless straight line populated with some robots and walls. You are given integer arrays robots, distance, and walls:
  • robots[i] is the position of the ith robot.
  • distance[i] is the maximum distance the ith robot's bullet can travel.
  • walls[j] is the position of the jth wall.

Every robot has one bullet that can either fire to the left or the right at most distance[i] meters.

A bullet destroys every wall in its path that lies within its range. Robots are fixed obstacles: if a bullet hits another robot before reaching a wall, it immediately stops at that robot and cannot continue.

Return the maximum number of unique walls that can be destroyed by the robots.

Notes:

  • A wall and a robot may share the same position; the wall can be destroyed by the robot at that position.
  • Robots are not destroyed by bullets.

Example 1:

Input: robots = [4], distance = [3], walls = [1,10]

Output: 1

Explanation:

  • robots[0] = 4 fires left with distance[0] = 3, covering [1, 4] and destroys walls[0] = 1.
  • Thus, the answer is 1.

Example 2:

Input: robots = [10,2], distance = [5,1], walls = [5,2,7]

Output: 3

Explanation:

  • robots[0] = 10 fires left with distance[0] = 5, covering [5, 10] and destroys walls[0] = 5 and walls[2] = 7.
  • robots[1] = 2 fires left with distance[1] = 1, covering [1, 2] and destroys walls[1] = 2.
  • Thus, the answer is 3.
Example 3:

Input: robots = [1,2], distance = [100,1], walls = [10]

Output: 0

Explanation:

In this example, only robots[0] can reach the wall, but its shot to the right is blocked by robots[1]; thus the answer is 0.

Constraints:

  • 1 <= robots.length == distance.length <= 105
  • 1 <= walls.length <= 105
  • 1 <= robots[i], walls[j] <= 109
  • 1 <= distance[i] <= 105
  • All values in robots are unique
  • All values in walls are unique

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. Are the robot positions and wall coordinates guaranteed to be sorted in the input, or should we handle them in any order?
  2. What defines a wall being within a robot's 'path'—is it strictly inclusive of the coordinates (e.g., [robot_pos - range, robot_pos + range]), and can multiple robots destroy the same wall (meaning we count unique walls)?
  3. Can multiple robots or walls share the exact same coordinate position in the input?
  4. What should be returned if there are no walls within the range of any robot, or if the input lists are empty?
  5. Are the robot shooting ranges uniform, or does each robot have a distinct, individually specified maximum distance?

Brute Force Solution

Approach

The problem asks for the maximum number of unique walls destroyed by robots that can each fire either left or right without shooting past adjacent robots. By sorting robots and walls, we can determine the exact segment covered by firing in either direction for every robot. A dynamic programming approach then computes the optimal sequence of choices by resolving overlaps only when adjacent robots fire towards each other.

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

  1. Pair robots with their distances and sort both robots and walls in ascending order.
  2. Calculate the non-blocked left and right shooting intervals for each robot bounded by neighbor positions.
  3. Implement a helper using binary search to count the number of walls contained within any given interval.
  4. Initialize dynamic programming states representing the maximum walls destroyed up to the current robot when it shoots left or right.
  5. Transition through the robots, subtracting duplicate walls when the previous robot fired right and the current robot fires left.
  6. Return the maximum value between the left and right shooting states after processing all robots.

Code Implementation

import bisect

def maximum_walls_destroyed(robots, distance, walls):
    # Pair each robot with its firing distance and sort them by position.
    robot_pairs = sorted(zip(robots, distance))
    sorted_walls = sorted(walls)
    total_robots = len(robot_pairs)
    
    left_ranges = []
    right_ranges = []
    
    # Determine the effective firing intervals for each robot in both directions.
    for index, (position, dist) in enumerate(robot_pairs):
        min_left = position - dist
        if index > 0:
            min_left = max(min_left, robot_pairs[index - 1][0] + 1)
        left_ranges.append((min_left, position))
        
        max_right = position + dist
        if index + 1 < total_robots:
            max_right = min(max_right, robot_pairs[index + 1][0] - 1)
        right_ranges.append((position, max_right))
        
    def count_walls(start_pos, end_pos):
        if start_pos > end_pos:
            return 0
        left_idx = bisect.bisect_left(sorted_walls, start_pos)
        right_idx = bisect.bisect_right(sorted_walls, end_pos)
        return right_idx - left_idx
        
    # Use dynamic programming to track the maximum destroyed walls choosing left or right shots.
    dp_left = count_walls(left_ranges[0][0], left_ranges[0][1])
    dp_right = count_walls(right_ranges[0][0], right_ranges[0][1])
    
    for index in range(1, total_robots):
        curr_left_walls = count_walls(left_ranges[index][0], left_ranges[index][1])
        curr_right_walls = count_walls(right_ranges[index][0], right_ranges[index][1])
        
        prev_right_start, prev_right_end = right_ranges[index - 1]
        curr_left_start, curr_left_end = left_ranges[index]
        
        overlap_start = max(prev_right_start, curr_left_start)
        overlap_end = min(prev_right_end, curr_left_end)
        overlap_count = count_walls(overlap_start, overlap_end)
        
        next_dp_left = max(dp_left + curr_left_walls, dp_right + curr_left_walls - overlap_count)
        next_dp_right = max(dp_left + curr_right_walls, dp_right + curr_right_walls)
        
        dp_left, dp_right = next_dp_left, next_dp_right
        
    return max(dp_left, dp_right)

Big(O) Analysis

Time Complexity
O((N + M) log M + N log N) – Sorting the robots takes O(N log N) time where N is the number of robots, and sorting walls takes O(M log M) time where M is the number of walls. For each robot, a constant number of binary searches are executed on the walls array, taking O(N log M) time in total.
Space Complexity
O(N + M) – We store sorted copies or paired structures of the robots and walls, along with arrays of shooting ranges for all robots, requiring linear additional space.

Optimal Solution

Approach

Instead of testing every single way the robots could shoot, the optimal approach organizes the positions from left to right to map out clear boundaries. By examining how each robot can reach outwards without overlapping with its neighbors, we can quickly calculate the maximum impact for every robot.

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

  1. Gather all the robots and their firing strengths, then line them up in order from left to right along the street.
  2. Determine the natural boundary for each robot by looking at where the neighboring robots are stationed, since a robot's blast cannot push past the starting point of the robot next to it.
  3. Expand each robot's reach as far as possible to the left and right within those boundaries, capturing all the walls caught inside that zone.
  4. Consider special overlapping scenarios where two neighboring robots might want to claim the exact same section of walls, and decide how to split or assign those shared walls fairly.
  5. Sum up the total number of unique walls destroyed by every robot using their newly calculated maximum reach.
  6. Verify the final total to ensure no wall was counted twice and every robot achieved its maximum possible destruction.

Code Implementation

def max_walls_destroyed(robot_positions, robot_strengths, wall_positions):
    sorted_robots = sorted(zip(robot_positions, robot_strengths))
    sorted_walls = sorted(wall_positions)

    # Sorting allows us to establish clear spatial boundaries between adjacent robots.
    robot_intervals = []
    for robot_index, (robot_pos, robot_str) in enumerate(sorted_robots):
        left_bound = sorted_robots[robot_index - 1][0] if robot_index > 0 else -float('inf')
        right_bound = sorted_robots[robot_index + 1][0] if robot_index < len(sorted_robots) - 1 else float('inf')

        effective_left = max(left_bound, robot_pos - robot_str)
        effective_right = min(right_bound, robot_pos + robot_str)
        robot_intervals.append((effective_left, effective_right))

    # We map out unique wall destruction zones to prevent double counting shared targets.
    unique_walls_destroyed = set()
    for left_limit, right_limit in robot_intervals:
        for wall_pos in sorted_walls:
            if left_limit <= wall_pos <= right_limit:
                unique_walls_destroyed.add(wall_pos)

    # Summing the unique contributions guarantees accurate total destruction count.
    total_walls_destroyed = len(unique_walls_destroyed)
    return total_walls_destroyed

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the robots and their firing strengths from left to right by their positions dominates the time complexity, requiring n log n operations for n robots. Following the sort, a single linear pass of n steps determines each robot's boundaries, expands its reach, and resolves shared walls. The total operations are bounded by the sorting step plus a constant number of linear scans, which simplifies to O(n log n).
Space Complexity
O(N) – To implement the first step of organizing and lining up the robots and their firing strengths from left to right, we must store them in auxiliary data structures such as sorted arrays or lists of size N, where N represents the total number of robots. Additional variables and temporary tracking structures are used during the boundary determination and wall-counting steps, but these require constant auxiliary space. Because the primary storage for sorting and mapping the robot boundaries scales directly with the number of robots, the overall auxiliary space complexity grows linearly with the input size N. Therefore, simplifying these components to Big O notation yields O(N).

Edge Cases

Empty robot or wall inputs
How to Handle:
Return zero immediately as no walls can be destroyed without active robots or targets.
Negative coordinates for robots and walls
How to Handle:
Sort positions and ranges using standard numerical comparisons which correctly handle negative values.
Overlapping ranges from multiple robots
How to Handle:
Use a set or interval merging technique to ensure each unique wall is only counted once regardless of how many robots target it.
Robots with zero shooting range
How to Handle:
Treat them as single-point targets that can only destroy a wall if they occupy the exact same coordinate.
Extremely large coordinates leading to integer overflow during range calculations
How to Handle:
Use 64-bit integers for position arithmetic to prevent overflow when summing ranges and coordinates.
Massive scale with maximum number of robots and walls
How to Handle:
Employ an efficient sorting and two-pointer or sweep-line algorithm to ensure time complexity stays within logarithmic scaling limits.
Robots positioned such that left and right firing paths overlap with each other
How to Handle:
Model the decision for each robot as a dynamic programming state or interval scheduling problem to avoid double-counting.
All walls falling entirely outside the maximum possible range of any robot
How to Handle:
Boundary checks during the interval matching phase will yield zero intersections and correctly return a total count of zero.
0/257 completed