Skip to main content
Back to problems
#1041
Medium Algorithms

Robot bounded in circle

Math String Simulation
56.5% acceptance
Feb 25, 2026
3859
717
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. The south direction is the negative direction of the y-axis. The east direction is the positive direction of the x-axis. The west direction is the negative direction of the x-axis. The robot can receive one of three instructions: "G": go straight 1 unit. "L": turn 90 degrees to the left (i.e., anti-clockwise direction). "R": turn 90 degrees to the right (i.e., clockwise direction). The robot performs the instructions given in order, and repeats them forever. Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn is_robot_bounded(instructions: String) -> bool {
    let (mut x, mut y) = (0i32, 0i32);
    // dir: 0=N,1=E,2=S,3=W
    let mut dir = 0usize;
    let dx = [0i32, 1, 0, -1];
    let dy = [1i32, 0, -1, 0];
    for c in instructions.chars() {
      match c {
        'G' => { x += dx[dir]; y += dy[dir]; }
        'L' => { dir = (dir + 3) % 4; }
        'R' => { dir = (dir + 1) % 4; }
        _ => {}
      }
    }
    (x == 0 && y == 0) || dir != 0
  }
}