Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
The robot repeatedly follows the rectangle's perimeter counterclockwise, so whole laps can be removed from large step counts. Position alone is not the full state: after a full lap to the origin it faces south, unlike its initial east-facing state.
Approach
Store position and a direction index cycling east, north, west, south. Reduce a positive step count modulo the perimeter length, but simulate one full perimeter if the remainder is zero so the final direction is updated correctly. For each remaining unit, attempt to move forward; if that leaves the rectangle, turn counterclockwise before moving. Position and direction queries read the stored state. A turn happens only when the next move would cross a boundary.
class Robot:
def __init__(self, width: int, height: int):
self.x, self.y = 0, 0
self.dirs = [(1, 0), (0, 1), (-1, 0), (0, -1)] # ENWS
self.d = 0
self.width = width
self.height = height
def step(self, num: int) -> None:
if num == 0: return
total = self.width * 2 + (self.height - 2) * 2
num %= total
if num == 0: num = total
for i in range(num):
nx, ny = self.x + self.dirs[self.d][0], self.y + self.dirs[self.d][1]
if nx < 0 or nx >= self.width or ny < 0 or ny >= self.height:
self.d = (self.d + 1) % 4
nx, ny = self.x + self.dirs[self.d][0], self.y + self.dirs[self.d][1]
self.x, self.y = nx, ny
def getPos(self) -> List[int]:
return [self.x, self.y]
def getDir(self) -> str:
if self.d == 0: return 'East'
elif self.d == 1: return 'North'
elif self.d == 2: return 'West'
else: return 'South'
# Your Robot object will be instantiated and called as such:
# obj = Robot(width, height)
# obj.step(num)
# param_2 = obj.getPos()
# param_3 = obj.getDir()Complexity analysis
Let P = 2 * width + 2 * height - 4 be the perimeter length. step(num) takes O(P) time in the worst case after perimeter reduction, and query methods take O(1) time; persistent and auxiliary space are O(1). Both reference implementations execute one full perimeter when a positive step is divisible by P, preserving the required direction.
