118. Back to Base

A warehouse robot starts at the origin of a grid. Its program is the string moves, where each character is one step of length one: U goes up, D goes down, L goes left and R goes right. The robot follows every instruction in order.

Return true if the robot is back exactly at the origin after the last step, and false otherwise. An empty path is not given; the program has at least one move. Track the position with two counters and do not store the visited cells.

Example 1

Input:
moves = "ULDR"
Output:
true
Explanation:

The robot goes up, left, down and right, which brings it back to the start.

Example 2

Input:
moves = "UUDL"
Output:
false
Explanation:

After the moves the robot is one column to the left and one row up, so it is not at the origin.

Constraints

1 ≤ moves.length ≤ 2 * 105

moves contains only the characters U, D, L and R

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…