Count Collisions on a Road LeetCode solution in Java

1
/*
2
cars on left side which are moving in left direction are never going to collide,
3
Similarly, cars on right side which are moving right side are never going to collide.
4

5
In between them every car is going to collide.
6
*/
7

8
class Solution {
9
public int countCollisions(String directions) {
10
int left = 0, right = directions.length() - 1;
11

12
while (left < directions.length() && directions.charAt(left) == 'L') {
13
left++;
14
}
15

16
while (right >= 0 && directions.charAt(right) == 'R') {
17
right--;
18
}
19

20
int count = 0;
21
for (int i = left; i <= right; i++) {
22
if (directions.charAt(i) != 'S') {
23
count++;
24
}
25
}
26
// combining these three loops - TC : O(N).
27

28
return count;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0