Last Updated: 27 Aug, 2020

Circular Move

Easy
Asked in companies
American ExpressAmazonCerner Corporation

Problem statement

You have a robot currently standing at the origin (0, 0) of a two-dimensional grid and facing north direction. You are given a sequence of moves for the robot in the form of a string of size 'N'. You are required to find whether the path followed by the robot upon taking the moves is circular or not.

A sequence of moves is circular if and only if the robot ends up from where it initially started.

The sequence of moves contains only three types of moves.

'G': it means that the robot will move 1 unit in the direction it is facing.

'L': it means that the robot will move 90 degrees towards its left. For example, if the robot is facing north and it has to make an ‘L’ move, then it will start facing the west direction.

'R': it means the robot will move 90 degrees towards its right. For example, if the robot is facing north and it has to make an ‘R’ move then it will start facing the east direction.
Input Format:
The first line contains an integer 'T' which denotes the number of test cases/queries to be run. 
Then the test cases follow. 

The first and the only line of input for each test case/query contains a string representing the sequence of moves.
Note:
The sequence of moves will always be:
1. A valid one.

2. In uppercase characters without spaces in between.
Output Format:
For each test case, print a single line containing ‘True’ if the sequence of moves is circular, print ‘False’ otherwise(without quotes).

The output for every test case will be printed in a separate line.
Note:
You do not need to print anything, it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 100
0 <= N <= 10 ^ 4

All the characters of the string will be ‘L’, ‘R’, and ‘G’.

Time Limit: 1 sec.

Approaches

01 Approach

Initialize a variable ‘direction’ with 0 which means that the robot is initially facing towards the north.

direction: 0 -> Robot is facing towards the North
direction: 1 -> Robot is facing towards the West 
direction: 2 -> Robot is facing towards the South 
direction: 3 -> Robot is facing towards the West

 

Initialize two variables ‘x’ and ‘y’ as 0. They will represent the position of the robot which is initially (0,0). Now, execute the moves from the sequence one by one and 

  • If the current move is  ‘L’ increase the direction by 1 and if the direction becomes 4 make it 0.
  • If the current move is ‘R’ then decrease the direction by 1 and if it becomes -1 then make it 3.
  • If the current move is ‘G’ then check the direction
    • If the direction is 0 then y = y + 1
    • If the direction is 1 then x = x - 1
    • If the direction is 2 then y = y - 1
    • If the direction is 3 then x = x + 1

Now simply check if the current position is (0,0) or not. If it is (0,0) then this sequence of moves is circular otherwise it is not circular.