Skip to content

2147. Number of Ways to Divide a Long Corridor 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  int numberOfWays(string corridor) {
    constexpr int kMod = 1'000'000'007;
    long ans = 1;
    int prevSeat = -1;
    int numSeats = 0;

    for (int i = 0; i < corridor.length(); ++i) {
      if (corridor[i] == 'S') {
        if (++numSeats > 2 && numSeats & 1)
          ans = ans * (i - prevSeat) % kMod;
        prevSeat = i;
      }
    }

    return numSeats > 1 && numSeats % 2 == 0 ? ans : 0;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public int numberOfWays(String corridor) {
    final int kMod = 1_000_000_007;
    long ans = 1;
    int prevSeat = -1;
    int numSeats = 0;

    for (int i = 0; i < corridor.length(); ++i) {
      if (corridor.charAt(i) == 'S') {
        if (++numSeats > 2 && numSeats % 2 == 1)
          ans = ans * (i - prevSeat) % kMod;
        prevSeat = i;
      }
    }

    return numSeats > 1 && numSeats % 2 == 0 ? (int) ans : 0;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def numberOfWays(self, corridor: str) -> int:
    kMod = 1_000_000_007
    ans = 1
    prevSeat = -1
    numSeats = 0

    for i, c in enumerate(corridor):
      if c == 'S':
        numSeats += 1
        if numSeats > 2 and numSeats & 1:
          ans = ans * (i - prevSeat) % kMod
        prevSeat = i

    return ans if numSeats > 1 and numSeats % 2 == 0 else 0