Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Robot Collisions

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2751" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

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). All integers in positions are unique. All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide. If two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line. Your task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final health of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array. Return an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur. Note: The positions may be unsorted. Example 1: 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]. Example 2: Input: positions = [3,5,2,6], healths = [10,10,15,12], directions = "RLRL" Output: [14] Explanation: There are 2 collisions in this example. Firstly, robot 1 and robot 2 will collide, and since both have the same health, they will be removed from the line. Next, robot 3 and robot 4 will collide and since robot 4's health is smaller, it gets removed, and robot 3's health becomes 15 - 1 = 14. Only robot 3 remains, so we return [14]. Example 3: Input: positions = [1,2,5,6], healths = [10,10,11,11], directions = "RLRL" Output: [] Explanation: Robot 1 and robot 2 will collide and since both have the same health, they are both removed. Robot 3 and 4 will collide and since both have the same health, they are both removed. So, we return an empty array, []. Constraints: 1 <= positions.length == healths.length == directions.length == n <= 105 1 <= positions[i], healths[i] <= 109 directions[i] == 'L' or directions[i] == 'R' All values in positions are distinct

Explanation

Here's the breakdown of the solution:

  • Sort and Simulate: Sort the robots based on their positions. Use a stack to simulate the collisions of right-moving robots with left-moving robots.
  • Collision Resolution: When a right-moving robot meets a left-moving robot, resolve the collision by comparing their healths. Update healths or remove robots as necessary.
  • Maintain Original Order: After collision resolution, reconstruct the final health array in the original robot order using the initial index information.

  • Runtime Complexity: O(n log n) due to sorting. Storage Complexity: O(n) for the stack and storing the initial robot information.

Code

    def survived_robots_healths(positions, healths, directions):
    n = len(positions)
    robots = []
    for i in range(n):
        robots.append((positions[i], healths[i], directions[i], i))

    robots.sort()  # Sort based on position

    stack = []
    survivors = []
    indices = set()
    for pos, health, direction, idx in robots:
        if direction == 'R':
            stack.append((health, idx))
        else:  # direction == 'L'
            while stack and health > 0:
                r_health, r_idx = stack[-1]
                if r_health > health:
                    health -= 1
                    stack[-1] = (r_health - 1, r_idx)
                    health = 0 # mark that the L robot is dead.
                elif r_health < health:
                    health -= r_health
                    stack.pop()
                else:
                    stack.pop()
                    health = 0 # mark that the L robot is dead.
                    break
            if health > 0:
                survivors.append((health, idx))
                indices.add(idx)

    while stack:
        health, idx = stack.pop()
        survivors.append((health, idx))
        indices.add(idx)

    survivors.sort(key=lambda x: x[1]) # important, sort by original indexes
    result = []
    for health, idx in survivors:
      result.append(health)
    return result

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Robot Collisions