Count Collisions on a Road — LeetCode 2211 Python Solution
MediumStackStringSimulation
- Problem
- #2211
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The 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.
Example
- Input
- directions = "RLRSLL"
- Output
- 5
- Explanation
- The collisions that will happen on the road are:
Python solution
Python
class Solution:
def countCollisions(self, directions: str) -> int:
s = directions.lstrip("L").rstrip("R")
return len(s) - s.count("S")Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) or O(1) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2211. Count Collisions on a Road is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2211. Count Collisions on a Road?
- LeetCode 2211. Count Collisions on a Road is rated Medium on LeetCode.
- What topics does LeetCode 2211. Count Collisions on a Road cover?
- LeetCode 2211. Count Collisions on a Road is tagged Stack, String and Simulation on LeetCode.