2026-04-01 20:54:07 +0300 MSK
Robot Collisions
Links
Code
class Solution:
def survivedRobotsHealths(
self, positions: List[int], healths: List[int], directions: str
) -> List[int]:
n = len(positions)
indices = list(range(n))
result = []
stack = deque()
# Sort indices based on their positions
indices.sort(key=lambda x: positions[x])
for current_index in indices:
# Add right-moving robots to the stack
if directions[current_index] == "R":
stack.append(current_index)
else:
while stack and healths[current_index] > 0:
# Pop the top robot from the stack for collision check
top_index = stack.pop()
if healths[top_index] > healths[current_index]:
# Top robot survives, current robot is destroyed
healths[top_index] -= 1
healths[current_index] = 0
stack.append(top_index)
elif healths[top_index] < healths[current_index]:
# Current robot survives, top robot is destroyed
healths[current_index] -= 1
healths[top_index] = 0
else:
# Both robots are destroyed
healths[current_index] = 0
healths[top_index] = 0
# Collect surviving robots
for index in range(n):
if healths[index] > 0:
result.append(healths[index])
return result