Problem 1041

Abstract / Summary

A robot moves on a grid following instructions and must be determined if it stays in a circle after repeating those instructions forever.

Note

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

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;
    }
};

38 lines | 901 bytes | submitted August 7, 2023 | GitHub   13% comment ratio | tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 57% (400k+ submissions).

Typical patterns to solve this problem:
  • Math
  • 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 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.

written by openai gpt

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.

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 = 6 | μ = 5.54 | σ = 1.67

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 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
31 links | 18 authors | 7 languages

Videos

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

Solved On The Same Day

40 easy 30 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