|
| 1 | +# [Problem 2211: Count Collisions on a Road](https://leetcode.com/problems/count-collisions-on-a-road/description/?envType=daily-question) |
| 2 | + |
| 3 | +## Initial thoughts (stream-of-consciousness) |
| 4 | +The cars move at the same speed; collisions only happen when paths cross. Cars that go left from the far left never meet anyone (they run away), and cars that go right from the far right never meet anyone. Any car that is moving and is not in those "escape" groups will eventually be involved in a collision (either head-on with another moving car or into a stationary car created by previous collisions). Each moving car that ends up stopped contributes one collision to the total count, and when two moving cars meet head-on both are counted — that gives 2 collisions for that event, but counting stopped moving cars captures that naturally. So maybe we can ignore the leading 'L's and trailing 'R's and count the rest of moving cars. |
| 5 | + |
| 6 | +## Refining the problem, round 2 thoughts |
| 7 | +Refinement: |
| 8 | +- Remove (ignore) all leading 'L' characters because they move left off to infinity and never collide. |
| 9 | +- Remove (ignore) all trailing 'R' characters because they move right off to infinity and never collide. |
| 10 | +- For the remaining segment, every 'L' or 'R' will eventually be involved in a collision and thus contributes 1 to the collision count. 'S' contributes 0. |
| 11 | +- Answer = count of characters in the middle segment that are not 'S'. |
| 12 | +Edge cases: |
| 13 | +- If all characters are leading L or trailing R (or both), the remaining segment may be empty -> return 0. |
| 14 | +Time/space: |
| 15 | +- Single pass to find boundaries and then a pass to count -> O(n) time, O(1) extra space. |
| 16 | + |
| 17 | +## Attempted solution(s) |
| 18 | +```python |
| 19 | +class Solution: |
| 20 | + def countCollisions(self, directions: str) -> int: |
| 21 | + n = len(directions) |
| 22 | + i = 0 |
| 23 | + # skip leading L (they go off to left) |
| 24 | + while i < n and directions[i] == 'L': |
| 25 | + i += 1 |
| 26 | + j = n - 1 |
| 27 | + # skip trailing R (they go off to right) |
| 28 | + while j >= 0 and directions[j] == 'R': |
| 29 | + j -= 1 |
| 30 | + if i > j: |
| 31 | + return 0 |
| 32 | + # count non-'S' in the remaining segment |
| 33 | + cnt = 0 |
| 34 | + for k in range(i, j + 1): |
| 35 | + if directions[k] != 'S': |
| 36 | + cnt += 1 |
| 37 | + return cnt |
| 38 | +``` |
| 39 | +- Notes: |
| 40 | + - Approach: skip cars that will never collide (leading 'L's and trailing 'R's), then every remaining moving car ('L' or 'R') will eventually stop due to collisions, so count them. |
| 41 | + - Time complexity: O(n) where n = len(directions) (two pointer scans and one pass in worst case). |
| 42 | + - Space complexity: O(1) extra space. |
| 43 | + - Implementation detail: handle the case i > j (empty middle segment) to return 0. |
0 commit comments