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.
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- Time: O(n)
- Space: O(1)