↓Skip to main content
  1. LeetCode/

LeetCode 657: Robot Return to Origin

·1 min· ·
LeetCode Easy String Simulation
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-08-29

  • Submissions: Accepted ×3

Approach
#

Up cancels down and left cancels right, so it suffices that U and D counts match and L and R counts match (Hash Table counting). Order does not matter.

My Solution
#

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        return moves.count("U") == moves.count("D") and moves.count("L") == moves.count("R")

Complexity
#

Time O(n), space O(1).

Mistakes to Avoid
#

  • Only the final position matters, not the order of moves.

Interview Explanation
#

Returning home means vertical and horizontal moves cancel, so I compare the counts of U with D and L with R. Time O(n).

Related

LeetCode 415: Add Strings
·2 mins
LeetCode Easy Math String Simulation
LeetCode 415 note: add digit by digit from the ends with two pointers, tracking the carry, and append any leftover carry after the loop
LeetCode 412: Fizz Buzz
·1 min
LeetCode Easy Math String Simulation
LeetCode 412 note: check multiples of 15 first, then 5 and 3; multiples need %, not //
LeetCode 67: Add Binary
·2 mins
LeetCode Easy Math String Bit-Manipulation Simulation
LeetCode 67 note: add from the ends of both strings digit by digit, with carry sum // 2 and digit sum % 2
LeetCode 557: Reverse Words in a String III
·1 min
LeetCode Easy Two-Pointers String
LeetCode 557 note: split on spaces, reverse each word, and join with spaces
LeetCode 500: Keyboard Row
·1 min
LeetCode Easy Array Hash-Table String
LeetCode 500 note: make a set for each keyboard row and keep words whose lowercase character set is a subset of one row
LeetCode 520: Detect Capital
·1 min
LeetCode Easy String
LeetCode 520 note: only three forms are valid: all caps, all lowercase, or only the first letter capitalized