C++ 1041.cpp
class Solution {
public:
bool isRobotBounded(string instructions) {
// 4x
instructions += instructions;
instructions += instructions;
int x = 0;
int y = 0;
int dx = 0;
int dy = +1;
for (auto i : instructions)
{
if (i == 'G')
{
x += dx;
y += dy;
continue;
}
// assume 'L'
if (dx == +1) { dx = 0; dy = +1; }
else if (dx == -1) { dx = 0; dy = -1; }
else if (dy == +1) { dx = -1; dy = 0; }
else { dx = +1; dy = 0; }
// flip
if (i == 'R')
{
dx = -dx;
dy = -dy;
}
}
return x == 0 && y == 0; // && dx == 0 && dy == +1;
}
};
Difficulty
and has an acceptance rate of about 57% (400k+ submissions).
Typical patterns to solve this problem:
- Math
- 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 presented implementation determines whether a robot that follows a sequence of movement instructions will remain within a bounded circle after executing the instructions repeatedly. The algorithm expands the original instruction string, simulates the robot’s motion, and finally checks the robot’s position to decide boundedness.
Instruction Expansion
The first logical block multiplies the instruction set fourfold:
instructions += instructions;
instructions += instructions;
By concatenating the original string with itself three times, the code creates a sequence that represents four consecutive executions of the original instructions. This expansion enables the simulation to observe the robot’s trajectory over multiple cycles without explicitly looping the simulation four times.
State Initialization
The robot’s state is represented by four integer variables:
int x = 0;
int y = 0;
int dx = 0;
int dy = +1;
(x, y) tracks the robot’s coordinates on a Cartesian plane, while (dx, dy) encodes the current heading direction. The initial heading points north (dx = 0, dy = +1). This explicit representation of direction as a vector simplifies subsequent updates for turns and forward moves.
Main Simulation Loop
The core of the algorithm iterates over each character in the expanded instruction string:
for (auto i : instructions)
{
if (i == 'G')
{
x += dx;
y += dy;
continue;
}
// assume 'L'
if (dx == +1) { dx = 0; dy = +1; }
else if (dx == -1) { dx = 0; dy = -1; }
else if (dy == +1) { dx = -1; dy = 0; }
else { dx = +1; dy = 0; }
// flip
if (i == 'R')
{
dx = -dx;
dy = -dy;
}
}
Forward Movement
When the current instruction is 'G', the robot advances one unit in its current heading. The update x += dx; y += dy; directly translates the direction vector into a positional change. The continue statement skips the turn-handling logic for this iteration, ensuring that only forward moves affect the coordinates.
Turning Logic
For any instruction that is not 'G', the code treats it as a left turn ('L') by default. The series of conditional assignments rotates the direction vector 90 degrees counter-clockwise:
- When facing east (
dx == +1), a left turn changes the heading to north (dx = 0; dy = +1). - When facing west (
dx == -1), a left turn changes the heading to south (dx = 0; dy = -1). - When facing north (
dy == +1), a left turn changes the heading to west (dx = -1; dy = 0). - Otherwise (facing south), a left turn changes the heading to east (
dx = +1; dy = 0).
Right Turn Adjustment
If the instruction is 'R', an additional “flip” step inverts both components of the direction vector:
dx = -dx;
dy = -dy;
Because the preceding block already performed a left turn, applying this sign inversion effectively converts the left turn into a right turn. This two-step approach consolidates the handling of both turn directions while keeping the code path compact.
Final Boundedness Check
After processing the quadruple instruction sequence, the algorithm evaluates the robot’s final position:
return x == 0 && y == 0;
If the robot returns to the origin after four cycles, the method concludes that the robot’s trajectory is bounded. The commented portion (&& dx == 0 && dy == +1) hints at an alternative condition that would also require the robot to face its original direction, but the current implementation relies solely on positional return.
Edge Cases Handled
The code naturally accommodates instruction strings that consist entirely of forward moves ('G'). In such cases, the robot’s coordinates will diverge from the origin, and the final check will correctly report an unbounded path.
When the instruction string contains only turn commands ('L' or 'R'), the robot never changes its coordinates, so the final position remains at the origin, leading to a bounded result.
Mixed sequences where the robot’s net displacement after one cycle is zero but its orientation changes are also covered. By repeating the instructions four times, the algorithm captures any cumulative effect of orientation changes that could otherwise cause drift over multiple cycles.
The handling of an empty instruction string is implicit: the expansion steps produce an empty string, the loop body never executes, and the robot stays at the origin, resulting in a bounded outcome.
Performance Optimizations
The most noticeable optimization is the pre-concatenation of the instruction string to represent four repetitions. This eliminates the need for an outer loop that would otherwise invoke the inner simulation four times. By flattening the repetitions into a single pass, the code reduces loop overhead and improves cache locality, as the iterator traverses a contiguous memory region.
Direction updates avoid modular arithmetic or lookup tables. The explicit conditional assignments for left turns and the sign inversion for right turns are simple integer operations, which are computationally inexpensive. This design sidesteps the need for more complex data structures such as arrays of direction vectors or enumerations, thereby minimizing memory accesses.
The early continue after processing a forward move prevents unnecessary evaluation of turn logic for 'G' instructions, ensuring that each character incurs only the operations required for its type. This selective execution path contributes to a tighter inner loop.
Overall, the algorithm runs in linear time relative to the length of the expanded instruction string, processing each character exactly once with a constant amount of work per iteration. The memory footprint remains modest, consisting of the original string (expanded in place) and a handful of integer variables.
ELI5 - Simplified Explanation
Imagine a little robot standing on a giant sheet of graph paper. The robot starts right in the middle at the spot marked zero for both across and up. It has a tiny compass that knows which way it is facing. At the very beginning, the robot is looking straight up towards the top of the paper.
The computer makes the instructions twice as long, and then twice as long again, just to make sure the robot has plenty of time to show where it is going. The robot looks at each instruction one by one. If it sees a letter that means go, it takes a step forward in the direction it is currently facing.
If the robot sees a turn command, it spins in place. Turning left twists the robot to a new direction, while turning right does the exact same thing but in the other way. The computer tracks the robot carefully by changing two numbers that represent the robot's left or right position and two numbers that represent its up or down position.
After the robot finishes all the steps, the computer looks at those final position numbers. If the robot ended up exactly back where it started at the very center, then the robot is stuck in a loop and will never wander off into space. If the numbers are not zero, it means the robot kept moving further and further away toward the edge of the paper.
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 | Go | TS | |||
| LeetcodeHelp | C++ | Python | Java | |||||
| Progiez | C++ | Python | Java | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| Garvit244 | Python | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| YuriSpiridonov | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| LeetcodeHelp | C++, Java, Python | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| Garvit244 | Python | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| YuriSpiridonov | Python |
Videos
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 657: Robot Return to Origin
- 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 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