# Robot Bounded In Circle

On an infinite plane, a robot initially stands at `(0, 0)` and faces north. The robot can receive one of three instructions:

• `"G"`: go straight 1 unit;
• `"L"`: turn 90 degrees to the left;
• `"R"`: turn 90 degrees to the right.

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.

Example 1:

Example 2:

Example 3:

Constraints:

• `1 <= instructions.length <= 100`
• `instructions[i]` is `'G'`, `'L'` or, `'R'`.

## Approach 1: One Pass

Intuition

This solution is based on two facts about the limit cycle trajectory.

• After at most 4 cycles, the limit cycle trajectory returns to the initial point `x = 0, y = 0`. That is related to the fact that 4 directions (north, east, south, west) define the repeated cycles' plane symmetry.

Algorithm

• Let’s use numbers from 0 to 3 to mark the directions: `north = 0`, `east = 1`, `south = 2`, `west = 3`. In the array `directions` we could store corresponding coordinates changes, i.e. `directions` is to go north, `directions` is to go east, `directions` is to go south, and `directions` is to go west.
• The initial robot position is in the center `x = y = 0`, facing north `idx = 0`.
• Now everything is ready to iterate over the instructions.
• If the current instruction is `R`, i.e. to turn on the right, the next direction is `idx = (idx + 1) % 4`. Modulo here is needed to deal with the situation - facing west, `idx = 3`, turn to the right to face north, `idx = 0`.
• If the current instruction is `L`, i.e. to turn on the left, the next direction could written in a symmetric way `idx = (idx - 1) % 4`. That means we have to deal with negative indices. A more simple way is to notice that 1 turn to the left = 3 turns to the right: `idx = (idx + 3) % 4`.
• If the current instruction is to move, we simply update the coordinates: `x += directions[idx]`, `y += directions[idx]`.
• After one cycle we have everything to decide. It’s a limit cycle trajectory if the robot is back to the center: `x = y = 0` or if the robot doesn't face north: `idx != 0`.

Complexity Analysis

• Time complexity: O(N), where N is a number of instructions to parse.
• Space complexity: O(1) because the array `directions` contains only 4 elements.

--

--