Leetcode 2211: Count Collisions on a Road

grid47
grid47
Exploring patterns and algorithms
Mar 30, 2024 5 min read

You have n cars on a straight road, each numbered from 0 to n-1 from left to right, with each car positioned at a unique location. You are given a string directions where each character represents the direction of a car (‘L’ for left, ‘R’ for right, and ‘S’ for stationary). Each moving car has the same speed, and the cars can collide under the following conditions: Two cars moving in opposite directions (‘L’ and ‘R’) will collide, counting as 2 collisions. A moving car colliding with a stationary car (‘S’) will result in 1 collision. After a collision, the cars involved stay at the collision point and no longer move. Your task is to calculate the total number of collisions that will happen.
Problem
Approach
Steps
Complexity
Input: The input is a 0-indexed string `directions` of length `n`, where each character is one of 'L', 'R', or 'S', denoting the direction of each car.
Example: "RSLSRL"
Constraints:
• 1 <= directions.length <= 10^5
• directions[i] is one of 'L', 'R', or 'S'.
Output: Return the total number of collisions that will happen.
Example: 4
Constraints:
• The output will be an integer representing the total number of collisions.
Goal: The goal is to count the number of collisions by checking when cars move in opposite directions or when moving cars collide with stationary cars.
Steps:
• Find the first car that moves towards the left and the last car that moves towards the right.
• Count the number of cars between them that collide based on the direction of movement and whether they are stationary.
Goal: The string `directions` is at least 1 character long and at most 10^5 characters long. Each character in `directions` is one of 'L', 'R', or 'S'.
Steps:
• 1 <= directions.length <= 10^5
• directions[i] is one of 'L', 'R', or 'S'.
Assumptions:
• The input string `directions` represents valid data with no other characters apart from 'L', 'R', or 'S'.
Input: "RSLSRL"
Explanation: The cars move in opposite directions, causing collisions between moving cars and stationary cars as they meet, and we count these interactions to get the total number of collisions.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus