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;
}
};
Difficulty
and has an acceptance rate of about 78% (800k+ submissions).
Typical patterns to solve this problem:
- Simulation
- String
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 547: Number of Provinces
- problem 2120: Execution of All Suffix Instructions Staying in a Grid
- problem 2833: Furthest Point From Origin
Solved On The Same Day
- problem 13: Roman to Integer
- problem 21: Merge Two Sorted Lists
- problem 28: Find the Index of the First Occurrence in a String
- problem 35: Search Insert Position
- problem 58: Length of Last Word
- problem 66: Plus One
- problem 67: Add Binary
- problem 69: Sqrt(x)
- problem 70: Climbing Stairs
- problem 206: Reverse Linked List
- problem 242: Valid Anagram
- problem 278: First Bad Version
- problem 283: Move Zeroes
- problem 367: Valid Perfect Square
- problem 374: Guess Number Higher or Lower
- problem 389: Find the Difference
- problem 441: Arranging Coins
- problem 459: Repeated Substring Pattern
- problem 509: Fibonacci Number
- problem 682: Baseball Game
- problem 704: Binary Search
- problem 709: To Lower Case
- problem 744: Find Smallest Letter Greater Than Target
- problem 746: Min Cost Climbing Stairs
- problem 860: Lemonade Change
- problem 896: Monotonic Array
- problem 976: Largest Perimeter Triangle
- problem 1137: N-th Tribonacci Number
- problem 1232: Check If It Is a Straight Line
- problem 1275: Find Winner on a Tic Tac Toe Game
- problem 1351: Count Negative Numbers in a Sorted Matrix
- problem 1491: Average Salary Excluding the Minimum and Maximum Salary
- problem 1502: Can Make Arithmetic Progression From Sequence
- problem 1523: Count Odd Numbers in an Interval Range
- problem 1539: Kth Missing Positive Number
- problem 1572: Matrix Diagonal Sum
- problem 1672: Richest Customer Wealth
- problem 1768: Merge Strings Alternately
- problem 1822: Sign of the Product of an Array
- problem 2: Add Two Numbers
- problem 5: Longest Palindromic Substring
- problem 33: Search in Rotated Sorted Array
- problem 34: Find First and Last Position of Element in Sorted Array
- problem 43: Multiply Strings
- problem 50: Pow(x, n)
- problem 54: Spiral Matrix
- problem 62: Unique Paths
- problem 63: Unique Paths II
- problem 64: Minimum Path Sum
- problem 73: Set Matrix Zeroes
- problem 74: Search a 2D Matrix
- problem 120: Triangle
- problem 139: Word Break
- problem 153: Find Minimum in Rotated Sorted Array
- problem 198: House Robber
- problem 221: Maximal Square
- problem 275: H-Index II
- problem 279: Perfect Squares
- problem 300: Longest Increasing Subsequence
- problem 436: Find Right Interval
- problem 445: Add Two Numbers II
- problem 528: Random Pick with Weight
- problem 540: Single Element in a Sorted Array
- problem 611: Valid Triangle Number
- problem 658: Find K Closest Elements
- problem 852: Peak Index in a Mountain Array
- problem 981: Time Based Key-Value Store
- problem 1041: Robot Bounded In Circle
- problem 1146: Snapshot Array
- problem 2300: Successful Pairs of Spells and Potions
- problem 154: Find Minimum in Rotated Sorted Array II
Extra
- 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