LeetCode 2211: Count Collisions on a Road Solution
Master LeetCode problem 2211 (Count Collisions on a Road), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
2211. Count Collisions on a Road
Problem Explanation
Explanation:
To solve this problem, we can iterate through the cars from left to right. For each car, we check if it is moving left or right. If it is moving right, we store its position. If it is moving left, we check if there are any cars that were moving right and have not collided yet. If there are, we calculate the collisions and update the total count. We repeat this process for all cars.
Algorithm:
- Initialize variables
collisionsto 0 and an empty setcarsMovingRight. - Iterate through the cars:
- If car i is moving right, add its position to
carsMovingRight. - If car i is moving left:
- Check for any cars moving right that haven't collided yet.
- Update
collisionsaccordingly.
- If car i is moving right, add its position to
- Return the total
collisions.
Time Complexity: O(n) where n is the number of cars.
Space Complexity: O(n) for storing the set of cars moving right.
:
Solution Code
class Solution {
public int countCollisions(String directions) {
int collisions = 0;
Set<Integer> carsMovingRight = new HashSet<>();
for (int i = 0; i < directions.length(); i++) {
if (directions.charAt(i) == 'R') {
carsMovingRight.add(i);
} else if (directions.charAt(i) == 'L') {
for (int pos : carsMovingRight) {
if (pos < i) {
collisions += 2;
} else {
collisions++;
}
}
}
}
return collisions;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 2211 (Count Collisions on a Road)?
This page provides optimized solutions for LeetCode problem 2211 (Count Collisions on a Road) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 2211 (Count Collisions on a Road)?
The time complexity for LeetCode 2211 (Count Collisions on a Road) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 2211 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2211 in Java, C++, or Python.