KatInterview

906. Walking Robot Simulation

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to simulate a robot's movement on an infinite 2D grid. The robot starts at (0, 0) facing North and receives a sequence of commands. These commands can be to turn left, turn right, or move forward. The grid contains obstacles. If the robot attempts to move onto a square with an obstacle, it stops at the previous square. Our goal is to find the maximum squared Euclidean distance from the origin (0, 0) the robot ever reaches during its movement.

Solution

Walking Robot Simulation in Python

class Solution:
    def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
        # Direction vectors: 0:N, 1:E, 2:S, 3:W
        dx = [0, 1, 0, -1]
        dy = [1, 0, -1, 0]
        
        # Current position and direction
        x, y = 0, 0
        direction = 0
        
        # Obstacle set for O(1) average time lookup
        obstacle_set = set(map(tuple, obstacles))
        
        max_squared_dist = 0
        
        for cmd in commands:
            if cmd == -1:  # Turn right 90 degrees
                direction = (direction + 1) % 4
            elif cmd == -2:  # Turn left 90 degrees
                direction = (direction - 1 + 4) % 4
            else:  # Move forward k units
                for _ in range(cmd):
                    next_x, next_y = x + dx[direction], y + dy[direction]
                    # Check if the next position is an obstacle
                    if (next_x, next_y) in obstacle_set:
                        break # Stop if obstacle is encountered
                    # Move to the next position
                    x, y = next_x, next_y
                # Update the maximum squared distance after the move command is complete
                max_squared_dist = max(max_squared_dist, x*x + y*y)
                
        return max_squared_dist

Walking Robot Simulation in Java

class Solution {
    public int robotSim(int[] commands, int[][] obstacles) {
        // Direction vectors: 0:N, 1:E, 2:S, 3:W
        int[] dx = {0, 1, 0, -1};
        int[] dy = {1, 0, -1, 0};
        
        int x = 0, y = 0;
        int direction = 0; // 0: North
        
        // Use a Set of strings "x,y" for efficient obstacle lookup.
        Set<String> obstacleSet = new HashSet<>();
        for (int[] obs : obstacles) {
            obstacleSet.add(obs[0] + "," + obs[1]);
        }
        
        // Use long for squared distance to prevent overflow during calculation
        long maxSquaredDist = 0;
        
        for (int cmd : commands) {
            if (cmd == -1) { // Turn right 90 degrees
                direction = (direction + 1) % 4;
            } else if (cmd == -2) { // Turn left 90 degrees
                direction = (direction + 3) % 4; // Same as (direction - 1 + 4) % 4
            } else { // Move forward k units
                for (int i = 0; i < cmd; ++i) {
                    int next_x = x + dx[direction];
                    int next_y = y + dy[direction];
                    // Check if the next position is an obstacle
                    if (obstacleSet.contains(next_x + "," + next_y)) {
                        break; // Stop if obstacle is encountered
                    }
                    // Move to the next position
                    x = next_x;
                    y = next_y;
                }
                // Update the maximum squared distance after the move command is complete
                maxSquaredDist = Math.max(maxSquaredDist, (long)x * x + (long)y * y);
            }
        }
        
        return (int)maxSquaredDist;
    }
}

Walking Robot Simulation in C++

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        // Direction vectors: 0:N, 1:E, 2:S, 3:W
        int dx[] = {0, 1, 0, -1};
        int dy[] = {1, 0, -1, 0};
        
        // Current position and direction
        int x = 0, y = 0;
        int direction = 0; // 0: North
        
        // Obstacle set for efficient lookup (O(log M) per lookup)
        std::set<std::pair<int, int>> obstacleSet;
        for (const auto& obs : obstacles) {
            obstacleSet.insert({obs[0], obs[1]});
        }
        
        // Use long long for squared distance to prevent overflow during calculation
        long long maxSquaredDist = 0;
        
        for (int cmd : commands) {
            if (cmd == -1) { // Turn right 90 degrees
                direction = (direction + 1) % 4;
            } else if (cmd == -2) { // Turn left 90 degrees
                direction = (direction + 3) % 4;
            } else { // Move forward k units
                for (int i = 0; i < cmd; ++i) {
                    int next_x = x + dx[direction];
                    int next_y = y + dy[direction];
                    // Check if the next position is an obstacle
                    if (obstacleSet.count({next_x, next_y})) {
                        break; // Stop if obstacle is encountered
                    }
                    // Move to the next position
                    x = next_x;
                    y = next_y;
                }
                // Update the maximum squared distance after the move command is complete
                maxSquaredDist = std::max(maxSquaredDist, (long long)x * x + (long long)y * y);
            }
        }
        
        return (int)maxSquaredDist;
    }
};

Walking Robot Simulation in TypeScript

function robotSim(commands: number[], obstacles: number[][]): number {
    // Direction vectors: 0:N, 1:E, 2:S, 3:W
    const dx = [0, 1, 0, -1];
    const dy = [1, 0, -1, 0];
    
    let x = 0;
    let y = 0;
    let direction = 0; // 0: North
    
    // Obstacle set for O(1) average time lookup, using a string key "x,y"
    const obstacleSet = new Set<string>();
    for (const obs of obstacles) {
        obstacleSet.add(`${obs[0]},${obs[1]}`);
    }
    
    let maxSquaredDist = 0;
    
    for (const cmd of commands) {
        if (cmd === -1) { // Turn right 90 degrees
            direction = (direction + 1) % 4;
        } else if (cmd === -2) { // Turn left 90 degrees
            direction = (direction + 3) % 4; // Same as (direction - 1 + 4) % 4
        } else { // Move forward k units
            for (let i = 0; i < cmd; i++) {
                const next_x = x + dx[direction];
                const next_y = y + dy[direction];
                // Check if the next position is an obstacle
                if (obstacleSet.has(`${next_x},${next_y}`)) {
                    break; // Stop if obstacle is encountered
                }
                // Move to the next position
                x = next_x;
                y = next_y;
            }
            // Update the maximum squared distance after the move command is complete
            maxSquaredDist = Math.max(maxSquaredDist, x * x + y * y);
        }
    }
    
    return maxSquaredDist;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.