Talentd
FleetCode
Make and follow sheets.Sign in

Walking Robot Simulation II solution and explanation

MediumDesignSimulation7 min read43.2% acceptanceUpdated 24 Mar 2026
Walking Robot Simulation II | Simplified Simulation | Leetcode 2069 | codestorywithMIKcodestorywithMIK · 24:31 · 6K viewsWatch on YouTube
9 more videos on this problem
  1. Walking Robot Simulation II | Simplified Simulation | Leetcode 2069 | codestorywithMIKcodestorywithMIK · 24:31 · 6K views
  2. 2069. Walking Robot Simulation II (Leetcode Medium)Programming Live with Larry · 20:55 · 1K views
  3. 2069. Walking Robot Simulation II | Leetcode Daily - PythonLeetcode Daily · 5:06 · 412 views
  4. leetcode 2069 | Walking Robot Simulation II | Simulation | Leetcode POTD | DSACode With Vick · 23:13 · 389 views
  5. Daily Leetcode #2198: Apr 07, 2026 - 2069. Walking Robot Simulation IIProgramming Live with Larry · 26:52 · 345 views
  6. Walking Robot Simulation II - Leetcode 2069 | Java | HindiKernel Queen 👑 · 14:04 · 319 views
  7. Walking Robot Simulation II | LeetCode 2069 - Pythonimpoldev · 11:28 · 300 views
  8. daily leetcode #2069 medium - "walking robot simulation II"Jaewon · 44:14 · 135 views
  9. Leetcode 2069 Walking Robot Simulation II - Explanation You Will Understand Easily!AlgorithmicIQ · 20:34 · 115 views
  10. Walking Robot Simulation II | LeetCode 2069 | Java Code | Developer CoderDeveloper Coder · 27:39 · 78 views

The problem

A width x height grid is on an XY-plane with the bottom-left cell at (0, 0) and the top-right cell at (width - 1, height - 1). The grid is aligned with the four cardinal directions ("North", "East", "South", and "West"). A robot is initially at cell (0, 0) facing direction "East".

The robot can be instructed to move for a specific number of steps. For each step, it does the following.

  1. Attempts to move forward one cell in the direction it is facing.
  2. If the cell the robot is moving to is out of bounds, the robot instead turns 90 degrees counterclockwise and retries the step.

After the robot finishes moving the number of steps required, it stops and awaits the next instruction.

Implement the Robot class:

  • Robot(int width, int height) Initializes the width x height grid with the robot at (0, 0) facing "East".
  • void step(int num) Instructs the robot to move forward num steps.
  • int[] getPos() Returns the current cell the robot is at, as an array of length 2, [x, y].
  • String getDir() Returns the current direction of the robot, "North", "East", "South", or "West".

Example 1:

example-1
Input
["Robot", "step", "step", "getPos", "getDir", "step", "step", "step", "getPos", "getDir"]
[[6, 3], [2], [2], [], [], [2], [1], [4], [], []]
Output
[null, null, null, [4, 0], "East", null, null, null, [1, 2], "West"]

Explanation
Robot robot = new Robot(6, 3); // Initialize the grid and the robot at (0, 0) facing East.
robot.step(2);  // It moves two steps East to (2, 0), and faces East.
robot.step(2);  // It moves two steps East to (4, 0), and faces East.
robot.getPos(); // return [4, 0]
robot.getDir(); // return "East"
robot.step(2);  // It moves one step East to (5, 0), and faces East.
                // Moving the next step East would be out of bounds, so it turns and faces North.
                // Then, it moves one step North to (5, 1), and faces North.
robot.step(1);  // It moves one step North to (5, 2), and faces North (not West).
robot.step(4);  // Moving the next step North would be out of bounds, so it turns and faces West.
                // Then, it moves four steps West to (1, 2), and faces West.
robot.getPos(); // return [1, 2]
robot.getDir(); // return "West"

Constraints:

  • 2 <= width, height <= 100
  • 1 <= num <= 105
  • At most 104 calls in total will be made to step, getPos, and getDir.

Approach overview

Problem Overview: Design a robot that walks along the boundary of a width × height grid. The robot starts at (0,0) facing East, moves step by step, turns counter‑clockwise at borders, and must report its current position and direction after any sequence of moves.

Approach 1: Direct Grid Simulation (O(k) time per move, O(1) space)

The straightforward solution simulates the robot one step at a time. Maintain the robot's (x, y) position and direction. For each step in move(num), attempt to move forward; if the next cell would leave the grid, rotate the direction counter‑clockwise and try again. This mirrors the exact rules of the problem and is easy to implement using a direction array and boundary checks. The downside is performance: a call like move(10^9) requires iterating all steps, making the method inefficient for large inputs. This approach mainly demonstrates the mechanics of simulation.

Approach 2: Circular Path Simplification (O(1) time per move, O(1) space)

The key observation: the robot never enters the interior of the grid. It only walks along the perimeter. The total perimeter cycle length is 2 × (width + height) − 4. Any movement larger than this simply repeats the same loop. Instead of simulating each step, reduce the movement using num % perimeter. Then advance along the four edges in order: bottom edge (east), right edge (north), top edge (west), and left edge (south). Update position and direction based on which segment the remaining steps fall into. Because the perimeter has only four segments, the update logic runs in constant time. This turns a potentially massive simulation into a small arithmetic calculation and fits naturally with a design style problem.

Recommended for interviews: The circular path simplification is the expected solution. It shows you recognized the perimeter cycle and eliminated unnecessary simulation. Implementing the direct simulation first can help verify the movement rules, but the optimized perimeter approach demonstrates stronger algorithmic thinking and system design awareness.

Approach 1: Circular Path Simplification

To solve this problem efficiently, we can treat the path as a large closed circuit along the perimeter of an enclosed rectangle. After a full circuit, the robot will find itself at the starting point facing East again. Let's compute the total perimeter and use this factively when moving the robot.

This way, movement simply becomes finding the correct position along this path and there's no need to simulate each individual step, hence reducing time complexity remarkably.

class Robot:
    def __init__(self, width: int, height: int):
        self.width = width
        self.height = height
        self.perimeter = 2 * (width + height) - 4
        self.position = 0
        self.directions = ['East', 'North', 'West', 'South']
        self.direction_index = 0

    def step(self, num: int):
        num %= self.perimeter
        while num > 0:
            if self.direction_index == 0:  # East
                move = min(num, self.width - 1 - self.position)
            elif self.direction_index == 1:  # North
                move = min(num, self.height - 1 - self.position)
            elif self.direction_index == 2:  # West
                move = min(num, self.position)
            else:  # South
                move = min(num, self.position)

            self.position += move
            num -= move

            if num > 0:
                self.direction_index = (self.direction_index + 1) % 4
                num -= 1
                self.position = 0

    def getPos(self) -> [int, int]:
        if self.direction_index == 0:
            return [self.position, 0]
        elif self.direction_index == 1:
            return [self.width - 1, self.position]
        elif self.direction_index == 2:
            return [self.width - 1 - self.position, self.height - 1]
        else:
            return [0, self.height - 1 - self.position]

    def getDir(self) -> str:
        return self.directions[self.direction_index]
public class Robot {
    private int width, height, perimeter, position;
    private int directionIndex;
    private final String[] directions = {"East", "North", "West", "South"};
    
    public Robot(int width, int height) {
        this.width = width;
        this.height = height;
        this.perimeter = 2 * (width + height) - 4;
        this.position = 0;
        this.directionIndex = 0;
    }
    
    public void step(int num) {
        num %= this.perimeter;
        while (num > 0) {
            int move = 0;
            switch (this.directionIndex) {
                case 0: // East
                    move = Math.min(num, width - 1 - position);
                    break;
                case 1: // North
                    move = Math.min(num, height - 1 - position);
                    break;
                case 2: // West
                    move = Math.min(num, position);
                    break;
                case 3: // South
                    move = Math.min(num, position);
                    break;
            }
            position += move;
            num -= move;

            if (num > 0) {
                directionIndex = (directionIndex + 1) % 4;
                num -= 1;
                position = 0;
            }
        }
    }
    
    public int[] getPos() {
        switch (directionIndex) {
            case 0: return new int[]{position, 0};
            case 1: return new int[]{width - 1, position};
            case 2: return new int[]{width - 1 - position, height - 1};
            default: return new int[]{0, height - 1 - position};
        }
    }

    public String getDir() {
        return directions[directionIndex];
    }
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct Robot {
    int width;
    int height;
    int perimeter;
    int position;
    int directionIndex;
    const char* directions[4];
} Robot;

Robot* robotCreate(int width, int height) {
    Robot* obj = (Robot*)malloc(sizeof(Robot));
    obj->width = width;
    obj->height = height;
    obj->perimeter = 2 * (width + height) - 4;
    obj->position = 0;
    obj->directionIndex = 0;
    obj->directions[0] = "East";
    obj->directions[1] = "North";
    obj->directions[2] = "West";
    obj->directions[3] = "South";
    return obj;
}

void robotStep(Robot* obj, int num) {
    num %= obj->perimeter;
    while (num > 0) {
        int move = 0;
        switch (obj->directionIndex) {
            case 0:
                move = (num < obj->width - 1 - obj->position ? num : obj->width - 1 - obj->position);
                break;
            case 1:
                move = (num < obj->height - 1 - obj->position ? num : obj->height - 1 - obj->position);
                break;
            case 2:
                move = (num < obj->position ? num : obj->position);
                break;
            case 3:
                move = (num < obj->position ? num : obj->position);
                break;
        }
        obj->position += move;
        num -= move;

        if (num > 0) {
            obj->directionIndex = (obj->directionIndex + 1) % 4;
            num--;
            obj->position = 0;
        }
    }
}

int* robotGetPos(Robot* obj) {
    int* pos = (int*)malloc(2 * sizeof(int));
    switch (obj->directionIndex) {
        case 0:
            pos[0] = obj->position;
            pos[1] = 0;
            break;
        case 1:
            pos[0] = obj->width - 1;
            pos[1] = obj->position;
            break;
        case 2:
            pos[0] = obj->width - 1 - obj->position;
            pos[1] = obj->height - 1;
            break;
        case 3:
            pos[0] = 0;
            pos[1] = obj->height - 1 - obj->position;
            break;
    }
    return pos;
}

char* robotGetDir(Robot* obj) {
    return (char*)obj->directions[obj->directionIndex];
}

The Robot class is initialized with the width and height of the grid, starting on the East of the point (0,0). The perimeter is calculated, which is the cycle the robot will travel.

Instead of attempting to move step by step, the robot calculates its new position by moving a specified number of steps along this 'track' efficiently using modulo arithmetic.

Complexity

Time Complexity: O(1) for each step, getPos, and getDir operations. Computation is constant, as moving steps is performed using arithmetic operations.

Space Complexity: O(1) as only a few variables are stored irrespective of input size.

Try this approach in the editor

Approach 2: Direct Grid Simulation

This approach involves directly simulating each step the robot makes on the grid. The robot's trajectory can be tracked direction by direction according to the edges and faces it is on. Turning and position updates are individually calculated for each potential movement.

class Robot:
    def __init__(self, width: int, height: int):
        self.x, self.y = 0, 0
        self.dir_index = 0
        self.width = width
        self.height = height
        self.directions = [(1, 0), (0, 1), (-1, 0), (0, -1)]
        self.dir_names = ['East', 'North', 'West', 'South']

    def step(self, num: int):
        for _ in range(num):
            dx, dy = self.directions[self.dir_index]
            nx, ny = self.x + dx, self.y + dy
            if 0 <= nx < self.width and 0 <= ny < self.height:
                self.x, self.y = nx, ny
            else:
                self.dir_index = (self.dir_index + 1) % 4

    def getPos(self) -> [int, int]:
        return [self.x, self.y]

    def getDir(self) -> str:
        return self.dir_names[self.dir_index]
class Robot {
    constructor(width, height) {
        this.x = 0;
        this.y = 0;
        this.dirIndex = 0;
        this.width = width;
        this.height = height;
        this.directions = [[1, 0], [0, 1], [-1, 0], [0, -1]];
        this.dirNames = ['East', 'North', 'West', 'South'];
    }

    step(num) {
        for (let i = 0; i < num; i++) {
            let [dx, dy] = this.directions[this.dirIndex];
            let nx = this.x + dx;
            let ny = this.y + dy;
            if (nx >= 0 && nx < this.width && ny >= 0 && ny < this.height) {
                this.x = nx;
                this.y = ny;
            } else {
                this.dirIndex = (this.dirIndex + 1) % 4;
            }
        }
    }

    getPos() {
        return [this.x, this.y];
    }

    getDir() {
        return this.dirNames[this.dirIndex];
    }
}
public class Robot {
    private int x, y;
    private int dirIndex;
    private int width, height;
    private readonly int[][] directions = new int[][] { new int[] { 1, 0 }, new int[] { 0, 1 }, new int[] { -1, 0 }, new int[] { 0, -1 } };
    private readonly string[] dirNames = { "East", "North", "West", "South" };

    public Robot(int width, int height) {
        this.x = 0;
        this.y = 0;
        this.dirIndex = 0;
        this.width = width;
        this.height = height;
    }

    public void Step(int num) {
        for (int i = 0; i < num; i++) {
            int nx = x + directions[dirIndex][0];
            int ny = y + directions[dirIndex][1];
            if (nx >= 0 && nx < width && ny >= 0 && ny < height) {
                x = nx;
                y = ny;
            } else {
                dirIndex = (dirIndex + 1) % 4;
            }
        }
    }

    public int[] GetPos() {
        return new int[] { x, y };
    }

    public string GetDir() {
        return dirNames[dirIndex];
    }
}

The robot executes its movement directly by attempting to walk in its current direction for each step. When a boundary is hit, it turns leftward. This simulation repeats through loop iteration.

Complexity

Time Complexity: O(num) per call to step due to simulating each step, making it suboptimal for large sequences.
Space Complexity: O(1) for storing direction, position, and state variables.

Try this approach in the editor

Complexity comparison

ApproachComplexity
Circular Path Simplification

Time Complexity: O(1) for each step, getPos, and getDir operations. Computation is constant, as moving steps is performed using arithmetic operations.

Space Complexity: O(1) as only a few variables are stored irrespective of input size.

Direct Grid Simulation

Time Complexity: O(num) per call to step due to simulating each step, making it suboptimal for large sequences.
Space Complexity: O(1) for storing direction, position, and state variables.

Complexity analysis

ApproachTimeSpaceWhen to Use
Direct Grid SimulationO(k) per moveO(1)When implementing a simple simulation or validating movement logic step by step
Circular Path SimplificationO(1) per moveO(1)Best approach when moves can be very large since the robot only cycles along the grid perimeter

Frequently asked questions

Is Walking Robot Simulation II easy or hard?

Walking Robot Simulation II is rated Medium on LeetCode. The challenge is recognizing that the robot only moves along the boundary and that its path forms a repeating cycle, which allows an O(1) solution instead of naive step-by-step simulation.

Walking Robot Simulation II Python/Java solution

Most implementations track the robot's position and direction, compute the perimeter length, and reduce movements using modulo. The remaining steps are applied along the four boundary edges. This logic translates cleanly to Python, Java, C, or other languages.

How to solve Walking Robot Simulation II in O(1)?

Compute the perimeter cycle length: 2 × (width + height) − 4. Reduce the requested movement using num % perimeter. Then determine which edge segment the remaining steps fall into and update the robot's position and direction accordingly.

What is the best approach for Walking Robot Simulation II?

The optimal approach is circular path simplification. The robot only walks along the grid perimeter, which has length 2 × (width + height) − 4. By reducing moves with modulo of the perimeter, you compute the final position and direction in constant time instead of simulating every step.

Is Walking Robot Simulation II asked at Google/Amazon/Meta?

Simulation and design problems like Walking Robot Simulation II appear frequently in interviews at large tech companies including Google, Amazon, and Meta. They test whether candidates can recognize patterns such as repeating cycles and avoid unnecessary brute-force simulation.

What data structure is used in Walking Robot Simulation II?

The solution mainly relies on simple variables for position and direction along with arithmetic on the grid perimeter. Some implementations use direction arrays or enums to track orientation, but no heavy data structures are required.

What is the time complexity of Walking Robot Simulation II?

The optimized perimeter approach runs in O(1) time per move because the robot's path repeats every perimeter cycle. A naive simulation that moves step by step requires O(k) time where k is the number of steps requested.

Comments

Now write it yourselfClose this page and solve Walking Robot Simulation II in the editor, without looking.
Practise Walking Robot Simulation II