Array ( [0] => [1] => questions [2] => Strings [3] => Move-Robot-in-circular )
Given a string K. You have to check if the sequence is circular or not. A sequence of moves is circular if first and last positions of robot are same. A move can be on of the following. G- Go one unit L-turn left R-turn right
First line contains the string K
Print yes if it can move in circular else print No.
GLGLGLGL
Yes
GLLG
Yes
GLRGLR
No
Login to see Discussion
Appraoch 1: using four different variables
step-i) initialize dir,up,down,right,left to 0
step-ii) assing 0 to i
step-iii) if character at index i is R then dir = (dir+1)%4
step-iv)else if character at index i is L then dir = (4+dir-1)%4
step-v)else if dir =0 increment up if dir=1 increment right if dir=2 increment down and if dir = 3 increment left
step-vi)if up equals to down and right equals to left return "Yes " else return "No"
Time Analysis: O(n) where n is the length of string
Space Analysis: O(1)
Appraoch 2: using two different variables
step-i) initialize dir,x,y to 0
step-ii) assing 0 to i
step-iii) if character at index i is R then dir = (dir+1)%4
step-iv)else if character at index i is L then dir = (4+dir-1)%4
step-v)else if dir =0 increment y if dir=1 increment x if dir=2 decrement x and if dir = 3 decremnet y
step-vi)if x equals to 0 and y equals to 0 return "Yes " else return "No"
Time Analysis: O(n) where n is the length of string
Space Analysis: O(1)
Note :
Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.
Login to see Solution