Count Collisions on a Road - Problem

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 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 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.

Input & Output

Example 1 — Basic Collision
$ Input: directions = "RLRSLL"
Output: 5
💡 Note: Cars move: R→, ←L, R→, S, ←L, ←L. The R at index 0 collides with L at index 1 (2 collisions). The R at index 2 collides with L at index 4 and L at index 5, and the stationary car gets hit (3 more collisions). Total = 5.
Example 2 — No Collisions
$ Input: directions = "LLRR"
Output: 0
💡 Note: All L cars move left, all R cars move right. Since L cars are on the left and R cars are on the right, they move away from each other. No collisions occur.
Example 3 — Stationary Cars
$ Input: directions = "RLSR"
Output: 2
💡 Note: R at index 0 moves right and collides with L at index 1 (2 collisions). They stop. The R at index 3 continues moving right without hitting anything.

Constraints

  • 1 ≤ directions.length ≤ 105
  • directions[i] is either 'L', 'R', or 'S'

Visualization

Tap to expand
Count Collisions on a RoadInput: RLRSLLRLRSLLCars collide when moving in opposite directionsor when moving car hits stationary carOutput: 5R=Right, L=Left, S=Stationary
Understanding the Visualization
1
Input
String with R (right), L (left), S (stationary) cars
2
Process
Cars move and collide, creating stationary masses
3
Output
Total number of collision events
Key Takeaway
🎯 Key Insight: Only cars between the leftmost R and rightmost L will be involved in collisions
Asked in
Google 15 Meta 12 Amazon 8
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen