Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created December 4, 2025 20:13
Show Gist options
  • Select an option

  • Save Ifihan/4f25c0fa9d635304d39bb40a25b6111e to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/4f25c0fa9d635304d39bb40a25b6111e to your computer and use it in GitHub Desktop.
Count Collisions on a Road

Question

Approach

I realize that cars that will never meet are the leading cars that move left ('L') and the trailing cars that move right ('R') — they run away from everyone else. If I trim those off the ends, every remaining moving car ('L' or 'R') will eventually be involved in a collision (and each contributes exactly one to the total count after accounting the opposed-pair +2 behavior). So I find the first index from the left that is not 'L' and the first index from the right that is not 'R', then count how many characters in that middle segment are not 'S'. That count is the answer.

Implementation

class Solution:
    def countCollisions(self, directions: str) -> int:
        n = len(directions)
        i = 0
        while i < n and directions[i] == 'L':
            i += 1
        j = n - 1
        while j >= 0 and directions[j] == 'R':
            j -= 1
        
        ans = 0
        for k in range(i, j + 1):
            if directions[k] != 'S':
                ans += 1
        return ans

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment