1236. Revisited Positions

A delivery robot starts at coordinates (0, 0) on an infinite grid and follows the string moves, one unit step per character: U raises y by 1, D lowers y by 1, L lowers x by 1 and R raises x by 1. The starting cell counts as the first visit to (0, 0), and every step adds one visit to the cell it lands on.

Return how many distinct cells receive at least two visits over the whole walk. A cell visited many times is still counted once. Track the visit count of every cell in a hash map keyed by the coordinate pair while you simulate the walk.

The intended solution runs in O(n) time and O(n) space, where n is the length of moves.

Example 1

Input:
moves = "UDUD"
Output:
2
Explanation:

The walk visits (0,0) three times and (0,1) twice, so two cells are visited at least twice.

Example 2

Input:
moves = "RRUU"
Output:
0
Explanation:

Every step lands on a new cell, so nothing is revisited.

Constraints

1 ≤ moves.length ≤ 2000

moves consists only of 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(n)

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…