Robot Return to Origin · Optimal Solution

Track displacement. Return means zero.

A robot starts at the origin on a 2D plane. Given a string of moves — U, D, L, R — determine whether the robot returns to the starting point. Each move shifts one axis by ±1.


Interactive

Watch the algorithm run


Concept

Independent Axes

The horizontal and vertical axes are independent. L/R change only the horizontal position; U/D change only the vertical position. The robot returns to the origin if and only if both final coordinates are zero.


Algorithm

Count and Compare

Track net displacement along two independent axes. The robot returns to the origin only when both axes cancel to zero.

  1. 1

    Initialize displacement

    Set h = 0 (horizontal) and v = 0 (vertical). The robot starts at the origin.

  2. 2

    Accumulate each move

    For each character: L decrements h, R increments h, U increments v, D decrements v.

  3. 3

    Check the origin

    After all moves, return true if and only if h == 0 and v == 0.


Edge Cases

Edge Patterns

Understanding boundary behavior is as important as the main algorithm path.

One axis balanced, one not

The move string "LRUD" has balanced horizontals but unbalanced verticals. Both must cancel for a return.

Empty string

No moves are made. The robot never leaves the origin — returns true.


Complexity

Complexity

Time: O(n) — single pass through the moves.
Space: O(1) — two integer counters.