Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #2751: Robot Collisions

In this guide, we solve Leetcode #2751 Robot Collisions in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

There are n 1-indexed robots, each having a position on a line, health, and movement direction. You are given 0-indexed integer arrays positions, healths, and a string directions (directions[i] is either 'L' for left or 'R' for right).

Quick Facts

  • Difficulty: Hard
  • Premium: No
  • Tags: Stack, Array, Sorting, Simulation

Intuition

The problem has a natural nested or last-in-first-out structure.

A stack lets us resolve matches in the correct order as we scan.

Approach

Push items as they appear and pop when you can finalize a decision.

The stack captures the unresolved part of the input.

Steps:

  • Push elements as you scan.
  • Pop when a rule or match is satisfied.
  • Use the stack to compute results.

Example

Input: positions = [5,4,3,2,1], healths = [2,17,9,15,10], directions = "RRRRR" Output: [2,17,9,15,10] Explanation: No collision occurs in this example, since all robots are moving in the same direction. So, the health of the robots in order from the first robot is returned, [2, 17, 9, 15, 10].

Python Solution

class Solution: def survivedRobotsHealths( self, positions: List[int], healths: List[int], directions: str ) -> List[int]: n = len(positions) indices = list(range(n)) stack = [] indices.sort(key=lambda i: positions[i]) for currentIndex in indices: if directions[currentIndex] == "R": stack.append(currentIndex) else: while stack and healths[currentIndex] > 0: topIndex = stack.pop() if healths[topIndex] > healths[currentIndex]: healths[topIndex] -= 1 healths[currentIndex] = 0 stack.append(topIndex) elif healths[topIndex] < healths[currentIndex]: healths[currentIndex] -= 1 healths[topIndex] = 0 else: healths[currentIndex] = 0 healths[topIndex] = 0 result = [health for health in healths if health > 0] return result

Complexity

The time complexity is O(n). The space complexity is O(n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy