1137. Torus Walker

Easy1.5 points estimatedSimulationHash TableString

A beetle walks on a small wrap-around garden board with m rows and n columns, starting on cell (0, 0). The string moves has one letter per step: 'U' moves one row up, 'D' one row down, 'L' one column left and 'R' one column right.

The board wraps at every edge, so stepping up from row 0 lands on row m-1, and stepping right from column n-1 lands on column 0. Return how many distinct cells the beetle stands on over the whole walk, counting the start cell. Keep the visited cells in a hash set keyed by row*n+col. Time is O(len(moves)) and space is O(len(moves)).

Example 1

Input:
m = 3, n = 3, moves = "RRRD"
Output:
4
Explanation:

The beetle visits (0,0), (0,1), (0,2), wraps back to (0,0), then reaches (1,0), so 4 distinct cells are visited.

Example 2

Input:
m = 2, n = 2, moves = "UDUD"
Output:
2
Explanation:

The beetle only alternates between (0,0) and (1,0), so 2 distinct cells are visited.

Constraints

1 ≤ m, n ≤ 104

1 ≤ moves.length ≤ 1000

Each character of moves is 'U', 'D', 'L' or '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(len(moves))
Space
O(len(moves))

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…