Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Horizontal and vertical displacement are independent. Every right move cancels one left move, and every up move cancels one down move. Since moves have equal length and fixed directions, their order does not affect the final position.

Approach

  1. Count the occurrences of the four move characters.
  2. Check that the number of upward moves equals the number of downward moves.
  3. Also check that left and right counts match. Return true only when both equalities hold. This tests the final position, without requiring the robot to stay near the origin or return there at any intermediate step.
class Solution: def judgeCircle(self, moves: str) -> bool: fm = Counter(moves) return fm['U'] == fm['D'] and fm['L'] == fm['R']

Complexity analysis

For n moves, counting characters takes O(n) time. The frequency map has at most four keys, so auxiliary space is O(1).