Sponsored
Sponsored
This approach involves counting the number of moves in each direction and checking if the horizontal movements ('L' and 'R') balance each other and the vertical movements ('U' and 'D') balance each other to return to the origin.
Time Complexity: O(n), where n is the length of the moves string.
Space Complexity: O(1), constant space used for variables x
and y
.
1#include <stdbool.h>
2
3bool judgeCircle(char* moves) {
4 int x = 0, y = 0;
5
6 for (int i = 0; moves[i] != '\0'; i++) {
7 char move = moves[i];
8 if (move == 'U') y++;
9 else if (move == 'D') y--;
10 else if (move == 'L') x--;
11 else if (move == 'R') x++;
12 }
13
14 return x == 0 && y == 0;
15}
We initialize two integer variables, x
and y
, to track the robot's position. We iterate through the moves
string, adjusting the position according to each move. If 'U' is found, y
is incremented; if 'D' is found, y
is decremented; 'L' decrements x
; and 'R' increments x
. Finally, we check if both x
and y
are zero, indicating a return to the origin, and return accordingly.
Instead of tracking coordinates, this approach counts the occurrences of each move character to determine if the robot returns to the origin. The idea is that the number of 'U' moves should equal 'D' moves and 'L' moves should equal 'R'.
Time Complexity: O(n), where n is the length of the input moves
.
Space Complexity: O(1), for direct counting with integer variables.
1#
We use four counters to track the number of each move type in the input string. The robot returns to the origin if 'U' matches 'D' and 'L' matches 'R'. Thus, we count the occurrences of each direction and compare. The function returns true if these conditions are met.