LeetCode Entry
2211. Count Collisions on a Road
Collisions R vs L
2211. Count Collisions on a Road medium blog post substack youtube

Join me on Telegram
https://t.me/leetcode_daily_unstoppable/1193
Problem TLDR
Collisions R vs L #medium
Intuition
Do separate pass for R, then backwards pass for L. Drop counter every time opposite meets.
Approach
- notice, only the prefix L and suffix R are excluded.
Complexity
-
Time complexity: \(O(n)\)
-
Space complexity: \(O(n)\), can be O(1)
Code
// 42ms
fun countCollisions(d: String) =
d.trimStart('L').trimEnd('R').count { it != 'S' }
// 0ms
pub fn count_collisions(d: String) -> i32 {
d.trim_start_matches('L').trim_end_matches('R').bytes()
.filter(|&b| b != b'S').count() as _
}