Member-only story

Solution to leetcode problem 1041: Robot Bounded In Circle

Pierre-Marie Poitevin
2 min readMay 18, 2019

--

In this Leetcode problem, we are asked if a robot given a set of moving instructions, and repeating them forever, is bounded in a circle or not.

Problem statement

To resolve this problem, you must notice a couple of facts:

  • If after the set of operations, the robot is still at the position (0, 0), then it is bounded
  • If the robot doesn’t point North after the set of instructions, it will return to the point (0, 0) after 4 sets of instructions, pointing North, and repeat. Therefore, if the robot doesn’t point North after the set of operations, it is bounded.
  • In all other cases, the robot is unbounded.

Then, in code, I executed the set of operations, tracking position and orientation of the robot. The end position and orientation tell me if the robot is bounded.

This can be done the following way, although tracking position with N, S, E, W symbols is a bit awkward, it should be easily understandable.

func isRobotBounded(instructions string) bool {
// robot is bounded if:
// end position is 0,0
// OR
// end direction is not North
direction := 'N'
x := 0
y := 0
for _, c := range instructions {
if c == 'G' {
if direction == 'N' {
y++
}…

--

--

Pierre-Marie Poitevin
Pierre-Marie Poitevin

Responses (2)