MediumNo. 1041

Robot Bounded In Circle — LeetCode 1041 Python Solution

Topics
Math, String, Simulation
Reading time
3 min

The problem

On an infinite plane, a robot initially stands at (0, 0) and faces north. Note that: The north direction is the positive direction of the y-axis.

Example

Input
instructions = "GGLLGG"
Output
true
Explanation
The robot is initially at (0, 0) facing the north direction.

Python solution

PythonSolution
class Solution:
    def isRobotBounded(self, instructions: str) -> bool:
        k = 0
        dist = [0] * 4
        for c in instructions:
            if c == 'L':
                k = (k + 1) % 4
            elif c == 'R':
                k = (k + 3) % 4
            else:
                dist[k] += 1
        return (dist[0] == dist[2] and dist[1] == dist[3]) or k != 0

Complexity

Time
O(n)
Space · auxiliary
O(1)where n is the length of the instruction string instructions

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1041. Robot Bounded In Circle is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0043Multiply StringsMedium
0412Fizz BuzzEasy
0415Add StringsEasy
0537Complex Number MultiplicationMedium
0592Fraction Addition and SubtractionMedium
0640Solve the EquationMedium

Frequently asked questions

How hard is LeetCode 1041. Robot Bounded In Circle?

LeetCode 1041. Robot Bounded In Circle is rated Medium on LeetCode.

What is the time complexity of LeetCode 1041. Robot Bounded In Circle?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 1041. Robot Bounded In Circle?

The Python solution on this page uses O(1), where n is the length of the instruction string \textit{instructions} auxiliary space.

What topics does LeetCode 1041. Robot Bounded In Circle cover?

LeetCode 1041. Robot Bounded In Circle is tagged Math, String and Simulation on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.