![]() |
VOOZH | about |
Given a sequence of moves for a robot, 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 one of the following.
G - Go one unit
L - Turn left
R - Turn right
Examples:
Input: path[] = "GLGLGLG"
Output: Given sequence of moves is circular
Input: path[] = "GLLG"
Output: Given sequence of moves is circular
The idea is to consider the starting position as (0, 0) and direction as East (We can pick any values for these). If after the given sequence of moves, we come back to (0, 0), then given sequence is circular, otherwise not.
N
|
|
W -------------- E
|
|
S
The move 'G' changes either x or y according to following rules.
- If current direction is North, then 'G' increments y and doesn't change x.
- If current direction is East, then 'G' increments x and doesn't change y.
- If current direction is South, then 'G' decrements y and doesn't change x.
- If current direction is West, then 'G' decrements x and doesn't change y.
The moves 'L' and 'R', do not change x and y coordinates, they only change direction according to following rule.
- If current direction is North, then 'L' changes direction to West and 'R' changes to East
- If current direction is East, then 'L' changes direction to North and 'R' changes to South
- If current direction is South, then 'L' changes direction to East and 'R' changes to West
- If current direction is West, then 'L' changes direction to South and 'R' changes to North.
Below is the implementation of above idea :
Given sequence of moves is circular
Time Complexity: O(n) where n is number of moves in given sequence.
Auxiliary Space: O(1)
Approach 2: Using a Hash Map
In this approach, we can maintain a hash map to store the count of the number of times the robot has visited a particular position. We can start from the initial position (0,0) and then update the position of the robot based on the moves given in the sequence. After completing the sequence, if the robot returns to the initial position and has not visited any other position more than once, then we can say that the sequence is circular.
In this approach, we maintain the current position and direction of the robot using two variables x and y and dir, respectively. We also maintain a hash map freq to store the frequency of each direction encountered in the path so far. For each character in the path, we update the position and direction of the robot and increment the frequency of the current direction in the hash map. After processing each move, we check if the robot has returned to the initial position and direction. If so, and if the frequency of each direction encountered so far is equal, then we conclude that the sequence of moves is circular. Otherwise, we continue processing the remaining moves.
The given sequence of moves is circular
Time Complexity: O(n) where n is the number of moves in the given sequence.
Auxiliary Space: O(n)