#657

Robot Return to Origin

Easy
StringSimulationHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Instead of tracking the robot's position step by step, we can count the occurrences of each move. The robot returns to the origin if the number of 'U's equals 'D's and 'L's equals 'R's.

⚙️

Algorithm

4 steps
  1. 1Step 1: Initialize counters for U, D, L, and R to zero.
  2. 2Step 2: Count each move in the string.
  3. 3Step 3: Check if the counts of U and D are equal and the counts of L and R are equal.
  4. 4Step 4: Return true if both conditions are met, otherwise return false.
solution.py2 lines
1def judgeCircle(moves):
2    return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R')

Complexity note: The time complexity is O(n) because we traverse the string a constant number of times (4 counts). The space complexity is O(1) since we only use a few counters.

  • 1The robot's movements can be balanced by counting opposing moves.
  • 2The problem can be solved efficiently without simulating each move.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.