Skip to content
Problem 657 · LeetCode 657(opens in a new tab)

Robot Return to Origin

EasySimulation

A robot starts at the point (0, 0) on a flat grid. It follows a string of instructions, moves, one character at a time. Each character moves it one unit: U goes up, D goes down, L goes left and R goes right. The robot’s facing does not matter; R always means one unit to the right.

Return true if the robot is standing on (0, 0) again after the last move, and false otherwise.

Example 1

Input:  moves = "RUDL"
Output: true
Why:    right, up, down, left: every step is undone
2 more examples and the constraints

Example 2

Input:  moves = "RRU"
Output: false
Why:    the robot ends at (2, 1)

Example 3

Input:  moves = "D"
Output: false
Why:    one step down and nothing brings it back

Constraints

  • 1 ≤ moves.length ≤ 20,000
  • moves contains only the characters U, D, L and R

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count each letterO(n)
  2. Track the positionO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeCharacter reads for 20,000 movesVerdict
Count each letterO(n)
Passes; four scans
Track the positionO(n)
Best; one scan, two numbers

n = the length of moves.

Edge cases to test

  • One move. A single move can never return home: "D" is false.
  • Odd length. Every return needs pairs of moves, so any odd length is false. The code handles it without a special case.
  • One axis balanced. "UDUDL" balances up and down but not left and right; both axes must be 0.
  • Scrambled order. "UULRDRLD" is true: the order of moves never matters.

Common mistakes

  • Checking only that the total number of moves is even.
  • Comparing U with R instead of U with D.
  • Returning early when the robot passes through (0, 0) in the middle.

How to talk through it

  1. 1Clarify. Does facing matter? Are the only letters U, D, L, R?
  2. 2Notice cancelling. Up undoes down and left undoes right, so only the counts matter.
  3. 3Pick the state. Two integers, x and y, are the whole state.
  4. 4Code one pass. Update x or y per character, then check both are 0.
  5. 5Test out loud. Try "D", "UD" and "UDUDL".
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?