[LeetCode] Count Collisions on a Road

2211. Count Collisions on a Road

There are n cars on an infinitely long road. The cars are numbered from 0 to n - 1 from left to right and each car is present at a unique point.

You are given a 0-indexed string directions of length n. directions[i] can be either ‘L’, ‘R’, or ‘S’ denoting whether the ith car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.

The number of collisions can be calculated as follows:

  • When two cars moving in opposite directions collide with each other, the number of collisions increases by 2.
  • When a moving car collides with a stationary car, the number of collisions increases by 1.

After a collision, the cars involved can no longer move and will stay at the point where they collided. Other than that, cars cannot change their state or direction of motion.

Return the total number of collisions that will happen on the road.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution {
public:
int countCollisions(string directions) {
int l = 0, r = 0, s = 0;
int res = 0;
for(auto ch : directions) {
if(ch == 'L') {
if(r) {
res += r + 1;
r = 0;
l = 0;
s = 1;
} else if(s) {
res++;
r = 0; l = 0; s = 1;
} else l++;
} else if(ch == 'R') {
l = 0; s = 0; r++;
} else {
if(r) {
res += r;
}
r = 0; l = 0; s = 1;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/03/20/PS/LeetCode/count-collisions-on-a-road/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.