Approach
Sorting and greedy selection
For Robot Collisions, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 45 lines of Python from the credited upstream file 2751.py.
- The implementation visibly relies on sequence storage.
- No explicit loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1from dataclasses import dataclass2 3 4@dataclass5class Robot:6 index: int7 position: int8 health: int9 direction: str10 11 12class Solution:13 def survivedRobotsHealths(14 self,15 positions: list[int],16 healths: list[int],17 directions: str,18 ) -> list[int]:19 robots = sorted([Robot(index, position, health, direction)20 for index, (position, health, direction) in21 enumerate(zip(positions, healths, directions))],22 key=lambda x: x.position)23 stack: list[Robot] = [] 24 25 for robot in robots:26 if robot.direction == 'R':27 stack.append(robot)28 continue29 30 while stack and stack[-1].direction == 'R' and robot.health > 0:31 if stack[-1].health == robot.health:32 stack.pop()33 robot.health = 034 elif stack[-1].health < robot.health:35 stack.pop()36 robot.health -= 137 else: 38 stack[-1].health -= 139 robot.health = 040 if robot.health > 0:41 stack.append(robot)42 43 stack.sort(key=lambda robot: robot.index)44 return [robot.health for robot in stack]45