Problem 657

Abstract / Summary

A robot moves using instructions north east south west and must end at its starting point after all moves.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0657.cpp

class Solution {
public:
    bool judgeCircle(string moves) {
        int x = 0, y = 0;
        for (auto m : moves)
            switch (m)
            {
                case 'U': y++; break;
                case 'D': y--; break;
                case 'R': x++; break;
                case 'L': x--; break;
            }

        return x == 0 && y == 0;
    }
};
16 lines | 379 bytes | submitted August 7, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 78% (800k+ submissions).

Typical patterns to solve this problem:
  • Simulation
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether a sequence of moves returns a point to its original position on a two-dimensional grid. It treats the input string as a series of directional commands-up, down, left, and right-and tracks the net displacement along the horizontal (x) and vertical (y) axes. After processing all characters, the function reports success only when both displacement counters are zero, indicating a closed loop.

Key Steps

The algorithm begins by establishing two integer counters that represent the current coordinates relative to the origin.

int x = 0, y = 0;

A range-based for loop iterates over each character in the input string, allowing direct access to each move without the overhead of index management.

for (auto m : moves)

Inside the loop a switch statement maps each possible character to an update of the appropriate coordinate. The four cases correspond to the four cardinal directions.

switch (m)
{
    case 'U': y++; break;
    case 'D': y--; break;
    case 'R': x++; break;
    case 'L': x--; break;
}

After all characters have been examined, the function evaluates whether the net displacement is zero on both axes and returns the boolean result.

return x == 0 && y == 0;

Edge Cases Handled

When the input string is empty, the loop body is never executed, leaving both x and y at their initial zero values. The final comparison therefore yields true, correctly indicating that no movement results in a return to the origin.

If the string contains a mixture of moves that cancel each other out-such as "UDLR" or any permutation where the count of 'U' equals the count of 'D' and the count of 'R' equals the count of 'L'-the incremental and decremental updates neutralize each other. The final coordinate check still reports true.

The switch statement implicitly ignores any character that does not match one of the four defined cases. Because there is no default branch, unrecognized characters produce no change to the counters, effectively treating them as no-ops. This behavior ensures that stray characters do not disrupt the displacement calculation.

Performance Optimizations

The solution processes the input in a single linear pass, updating only two integer variables. This approach eliminates the need for auxiliary data structures such as arrays, hash maps, or stacks, thereby keeping the memory footprint minimal and constant regardless of input length.

Using a range-based for loop avoids repeated calls to size() or manual index arithmetic, which can reduce overhead in tight loops. The auto type deduction for the loop variable yields a lightweight copy of each character, avoiding unnecessary references.

The switch construct is compiled into a jump table when the case values are dense and known at compile time. This yields faster dispatch compared to a series of if-else statements, especially when the number of cases is small and fixed.

Increment and decrement operations on primitive integers are performed in constant time and are highly optimized by modern processors. By directly modifying the counters rather than accumulating intermediate objects, the code benefits from efficient register usage and minimal instruction count.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a little robot standing on a giant piece of grid paper. The robot starts right in the middle at a point called zero zero. The moves represent instructions given to the robot to help it walk around. When the robot sees the letter U, it takes one step up. When it sees D, it takes one step down. When it sees R, it takes one step to the right, and when it sees L, it takes one step to the left. The code goes through every single instruction one by one to keep track of exactly where the robot ends up after all that walking. If the robot finishes its journey back at the very same spot where it started, it means the robot made a perfect circle.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 8.31 | σ = 0.61

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java Rust JS Go TS
LeetcodeHelp C++ Python Java
Progiez C++ Python Java
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fengvyi C++
JoshCrozier JS
keineahnung2345 C++
Krazune C#
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
DimitrisJim C
fartem Ruby
fengvyi C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C#
lkwq007 Python
lzl124631x C++
muhammadfarhankt Go
ruoru Rust
suxrobGM C#
varunu28 Java
withaarzoo C++
YuriSpiridonov Python
zfang399 C++
38 links | 23 authors | 10 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

39 easy 31 medium 1 hard
72 solutions   August 7, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality