Coding interview practice · LeetCode 1041
A robot begins at the origin, facing north. It repeats the same instruction string forever. How can we decide, after simulating that string just once, whether its entire path stays inside a fixed circle?
GMove forward one unitLTurn left by 90°RTurn right by 90°The answer below develops the proof, walks through examples and gives a tested Python implementation. Practice the original problem on LeetCode ↗
Qaskme editorial coding Q&A, published at the site owner’s request with an AI-assisted explanation and independently tested code. Independent interview practice material.
Editorial answer · Explanation + Python solution
The one-pass test
You only need the final position and direction. There is no need to store every visited point or run the instructions indefinitely.
Why this works
Think of one complete instruction string as a single movement pattern. Each repetition has the same shape, rotated to match the robot’s starting direction.
For the last case, the displacement vectors are the same vector rotated by 0°, 90°, 180° and 270°. Their sum is zero. Since the repeating route consists of finitely many steps, a circle can enclose the whole route.
Python 3 solution
Represent north with the direction vector
(0, 1). A left turn changes(dx, dy)to(-dy, dx); a right turn changes it to(dy, -dx).Command correction: LeetCode uses
Gfor “go forward”. If an assessment variant usesSinstead, change that comparison to match its statement. Do not useSwhen submitting to this LeetCode problem.Examples
GGLLGG(0, 0), facing south.trueGG(0, 2), still facing north.falseGL(0, 1), facing west.trueA closer look at
GLEach pass moves forward once and turns left. The end states show how a changed heading closes the route:
(0, 1)(-1, 1)(-1, 0)(0, 0)Complexity and edge cases
Code verification: checked against all 9,840 valid command strings of lengths 1–8, eight explicit examples and four maximum-length cases. The independent reference simulator executes four full passes and checks for a return to the origin.
Problem reference: LeetCode 1041 — Robot Bounded In Circle. The explanation and implementation here are Qaskme’s AI-assisted editorial practice material.