Skip to content

2211. Count Collisions on a Road

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int countCollisions(string directions) {
    int l = 0;
    int r = directions.length() - 1;

    while (l < directions.length() && directions[l] == 'L')
      ++l;

    while (r >= 0 && directions[r] == 'R')
      --r;

    return count_if(directions.begin() + l, directions.begin() + r + 1,
                    [](char c) { return c != 'S'; });
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int countCollisions(String directions) {
    int ans = 0;
    int l = 0;
    int r = directions.length() - 1;

    while (l < directions.length() && directions.charAt(l) == 'L')
      ++l;

    while (r >= 0 && directions.charAt(r) == 'R')
      --r;

    for (int i = l; i <= r; ++i)
      if (directions.charAt(i) != 'S')
        ++ans;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def countCollisions(self, directions: str) -> int:
    l = 0
    r = len(directions) - 1

    while l < len(directions) and directions[l] == 'L':
      l += 1

    while r >= 0 and directions[r] == 'R':
      r -= 1

    return sum(c != 'S' for c in directions[l:r + 1])