MediumNo. 2211

Count Collisions on a Road — LeetCode 2211 Python Solution

Pattern
Stack
Topics
Stack, String, Simulation
Reading time
2 min

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

PythonSolution
class Solution:
    def countCollisions(self, directions: str) -> int:
        s = directions.lstrip("L").rstrip("R")
        return len(s) - s.count("S")

Complexity

Time
O(n)
Space · auxiliary
O(n) or O(1)

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.