#2069

Walking Robot Simulation II

Medium
DesignSimulationSimulationModular Arithmetic
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of simulating each step, we can calculate the final position using modular arithmetic based on the perimeter of the grid. This allows us to determine the robot's position and direction efficiently.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the perimeter of the grid as 2 * (width + height).
  2. 2Step 2: Use the total steps modulo the perimeter to find the effective steps the robot takes.
  3. 3Step 3: Determine the final position and direction based on the effective steps.
solution.py38 lines
1class Robot:
2    def __init__(self, width: int, height: int):
3        self.width = width
4        self.height = height
5        self.perimeter = 2 * (width + height)
6        self.x, self.y = 0, 0
7        self.directions = ['East', 'North', 'West', 'South']
8        self.dir_index = 0
9
10    def step(self, num: int):
11        effective_steps = num % self.perimeter
12        for _ in range(effective_steps):
13            if self.dir_index == 0:
14                if self.x + 1 < self.width:
15                    self.x += 1
16                else:
17                    self.dir_index = 1
18            elif self.dir_index == 1:
19                if self.y + 1 < self.height:
20                    self.y += 1
21                else:
22                    self.dir_index = 2
23            elif self.dir_index == 2:
24                if self.x - 1 >= 0:
25                    self.x -= 1
26                else:
27                    self.dir_index = 3
28            else:
29                if self.y - 1 >= 0:
30                    self.y -= 1
31                else:
32                    self.dir_index = 0
33
34    def getPos(self):
35        return [self.x, self.y]
36
37    def getDir(self):
38        return self.directions[self.dir_index]

Complexity note: The time complexity is O(n) because we only loop through the effective steps, which is at most the perimeter of the grid. The space complexity is O(1) since we only use a fixed amount of space.

  • 1The robot only moves along the perimeter of the grid, which can be leveraged to optimize the movement calculations.
  • 2Using modular arithmetic allows for quick determination of the robot's position after many steps.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.