Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Walking Robot Simulation

Updated
4 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "874" 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

A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot receives an array of integers commands, which represents a sequence of moves that it needs to execute. There are only three possible types of instructions the robot can receive: -2: Turn left 90 degrees. -1: Turn right 90 degrees. 1 <= k <= 9: Move forward k units, one unit at a time. Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, it will stay in its current location (on the block adjacent to the obstacle) and move onto the next command. Return the maximum squared Euclidean distance that the robot reaches at any point in its path (i.e. if the distance is 5, return 25). Note: There can be an obstacle at (0, 0). If this happens, the robot will ignore the obstacle until it has moved off the origin. However, it will be unable to return to (0, 0) due to the obstacle. North means +Y direction. East means +X direction. South means -Y direction. West means -X direction. Example 1: Input: commands = [4,-1,3], obstacles = [] Output: 25 Explanation: The robot starts at (0, 0): Move north 4 units to (0, 4). Turn right. Move east 3 units to (3, 4). The furthest point the robot ever gets from the origin is (3, 4), which squared is 32 + 42 = 25 units away. Example 2: Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]] Output: 65 Explanation: The robot starts at (0, 0): Move north 4 units to (0, 4). Turn right. Move east 1 unit and get blocked by the obstacle at (2, 4), robot is at (1, 4). Turn left. Move north 4 units to (1, 8). The furthest point the robot ever gets from the origin is (1, 8), which squared is 12 + 82 = 65 units away. Example 3: Input: commands = [6,-1,-1,6], obstacles = [[0,0]] Output: 36 Explanation: The robot starts at (0, 0): Move north 6 units to (0, 6). Turn right. Turn right. Move south 5 units and get blocked by the obstacle at (0,0), robot is at (0, 1). The furthest point the robot ever gets from the origin is (0, 6), which squared is 62 = 36 units away. Constraints: 1 <= commands.length <= 104 commands[i] is either -2, -1, or an integer in the range [1, 9]. 0 <= obstacles.length <= 104 -3 104 <= xi, yi <= 3 104 The answer is guaranteed to be less than 231.

Explanation

Here's the breakdown of the solution:

  • Simulate the Robot's Movements: Iterate through the commands array, updating the robot's position and direction based on each command.
  • Obstacle Detection: Before each forward movement, check if the next cell is an obstacle. If it is, prevent the movement.
  • Track Maximum Distance: Keep track of the maximum squared Euclidean distance the robot has reached from the origin throughout the simulation.

  • Runtime Complexity: O(m + n), where m is the number of commands and n is the number of obstacles.

  • Storage Complexity: O(n), where n is the number of obstacles.

Code

    def robot_sim(commands, obstacles):
    """
    Simulates the robot's movements and returns the maximum squared Euclidean distance from the origin.

    Args:
        commands: A list of integers representing the robot's movement commands.
        obstacles: A list of lists, where each inner list represents the coordinates of an obstacle.

    Returns:
        The maximum squared Euclidean distance the robot reaches.
    """

    # Directions: North, East, South, West
    directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
    current_direction = 0  # Start facing North

    x, y = 0, 0  # Initial position
    max_distance_squared = 0

    obstacle_set = set((obs[0], obs[1]) for obs in obstacles)  # Convert obstacles to a set for faster lookup

    for command in commands:
        if command == -2:  # Turn left
            current_direction = (current_direction - 1) % 4
        elif command == -1:  # Turn right
            current_direction = (current_direction + 1) % 4
        else:  # Move forward
            for _ in range(command):
                next_x = x + directions[current_direction][0]
                next_y = y + directions[current_direction][1]

                if (next_x, next_y) in obstacle_set:
                    break  # Stop moving if there's an obstacle
                else:
                    x, y = next_x, next_y
                    max_distance_squared = max(max_distance_squared, x * x + y * y)

    return max_distance_squared

More from this blog

C

Chatmagic blog

2894 posts