#3661

Maximum Walls Destroyed by Robots

Hard
ArrayBinary SearchDynamic ProgrammingSortingHash 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)

Sort robots and walls, then use binary search to efficiently find the range of walls affected by each robot.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort robots and walls arrays.
  2. 2Step 2: For each robot, calculate the effective range and use binary search to find walls within that range.
  3. 3Step 3: Use a set to count unique walls destroyed.
solution.py14 lines
1def maxWallsDestroyed(robots, distance, walls):
2    robots.sort()
3    walls.sort()
4    destroyed = set()
5    for i in range(len(robots)):
6        left = robots[i] - distance[i]
7        right = robots[i] + distance[i]
8        for wall in walls:
9            if wall < left:
10                continue
11            if wall > right:
12                break
13            destroyed.add(wall)
14    return len(destroyed)

Complexity note: Sorting takes O(n log n), and checking walls takes O(n) for each robot.

  • 1Sorting helps in efficiently checking ranges.
  • 2Using sets avoids counting duplicates.

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