Count Collisions on a Road - Problem
Count Collisions on a Road
Imagine a busy highway with
When cars collide, they create traffic chaos! The collision rules are:
After any collision, all involved cars become stationary and remain at the collision point forever.
Goal: Calculate the total number of collisions that will occur on this chaotic road!
Imagine a busy highway with
n cars positioned at unique points along an infinitely long road. Each car has one of three behaviors:- 'L' - Moving left at constant speed
- 'R' - Moving right at constant speed
- 'S' - Stationary (parked)
When cars collide, they create traffic chaos! The collision rules are:
- Moving car vs Moving car: +2 collisions (both cars involved)
- Moving car vs Stationary car: +1 collision (only moving car counts)
After any collision, all involved cars become stationary and remain at the collision point forever.
Goal: Calculate the total number of collisions that will occur on this chaotic road!
Input & Output
example_1.py โ Basic Collision
$
Input:
directions = "RLRSLL"
โบ
Output:
5
๐ก Note:
Cars at positions 0(R) and 1(L) collide head-on (+2). Car at 0 becomes S. Car at 2(R) hits the now-stationary car at 1 (+1). Car at 4(L) hits stationary car at 3(S) (+1). Car at 5(L) hits the now-stationary car at 4 (+1). Total: 2+1+1+1=5
example_2.py โ No Collisions
$
Input:
directions = "LLRR"
โบ
Output:
0
๐ก Note:
Left-moving cars (LL) move away from right-moving cars (RR). No cars are moving toward each other, so no collisions occur.
example_3.py โ Complex Scenario
$
Input:
directions = "SSRSSRLLRSLS"
โบ
Output:
20
๐ก Note:
Multiple collision zones form barriers. Cars between positions 2 and 11 are trapped in collision zones. Each moving car (R or L) in this zone contributes 1 collision: R(3)+R(5)+L(6)+L(7)+R(8)+S(9)+L(10) = 6 moving cars = 6 collisions. Wait, let me recalculate properly using the optimal approach...
Constraints
- 1 โค directions.length โค 105
- directions[i] is either 'L', 'R', or 'S'
- Each car has a unique position on the road
- All moving cars travel at the same constant speed
Visualization
Tap to expand
Understanding the Visualization
1
Identify Escape Routes
Cars at the start moving left can escape. Cars at the end moving right can escape.
2
Find Collision Zone
The area between the first barrier (left) and last barrier (right) traps cars.
3
Count Trapped Cars
Every moving car in the collision zone will crash and contribute 1 collision.
4
Calculate Total
Sum up all the individual collisions in the trapped zone.
Key Takeaway
๐ฏ Key Insight: Cars only collide when trapped between barriers. By finding the collision zone boundaries, we can count all collisions in O(n) time without simulating actual movement!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code