One axis balanced, one not
The move string "LRUD" has balanced horizontals but unbalanced verticals. Both must cancel for a return.
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.
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.
Track net displacement along two independent axes. The robot returns to the origin only when both axes cancel to zero.
Set h = 0 (horizontal) and v = 0 (vertical). The robot starts at the origin.
For each character: L decrements h, R increments h, U increments v, D decrements v.
After all moves, return true if and only if h == 0 and v == 0.
Understanding boundary behavior is as important as the main algorithm path.
The move string "LRUD" has balanced horizontals but unbalanced verticals. Both must cancel for a return.
No moves are made. The robot never leaves the origin — returns true.
Time: O(n) — single pass through the moves.
Space: O(1) — two integer counters.