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 receive a 0-indexed string directions of length n. directions[i] can be either 'L', 'R', or 'S' denoting whether the i^th car is moving towards the left, towards the right, or staying at its current point respectively. Each moving car has the same speed.
The count of collisions can be calculated as follows:
-
When two cars moving in opposite directions collide with each other, the count of collisions increases by
2. -
When a moving car collides with a stationary car, the count 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.
Find and provide the total count of collisions that will happen on the road.
Input: directions = "RLRSLL"
Output: 5
Explanation: The collisions that will happen on the road are:
-
Cars 0 and 1 will collide with each other. Since they are moving in opposite directions, the count of collisions becomes 0 + 2 = 2.
-
Cars 2 and 3 will collide with each other. Since car 3 is stationary, the count of collisions becomes 2 + 1 = 3.
-
Cars 3 and 4 will collide with each other. Since car 3 is stationary, the count of collisions becomes 3 + 1 = 4.
-
Cars 4 and 5 will collide with each other. After car 4 collides with car 3, it will stay at the point of collision and get hit by car 5. The count of collisions becomes 4 + 1 = 5.
Thus, the total count of collisions that will happen on the road is 5.
Input: directions = "LLRR"
Output: 0
Explanation: No cars will collide with each other. Thus, the total count of collisions that will happen on the road is 0.
Constraints
1 <= directions.length <= 10^5directions[i]is either'L','R', or'S'.
Did this problem appear in one of your interviews?
Responses stay private.
