Number of Ways to Divide a Long Corridor

hard combinatorics counting string

Problem

A corridor is a string of seats ('S') and plants ('P'). Dividers already sit just left of index 0 and just right of the last index; you may add more dividers between adjacent positions. Split the corridor into non-overlapping sections so that each section has exactly two seats (and any number of plants). Return the number of distinct ways, modulo 109+7; return 0 if it is impossible.

Inputcorridor = "SSPPSPS"
Output3
The 2nd and 3rd seats sit at indices 1 and 4, so the divider between the two sections has 4 − 1 = 3 legal positions.
Inputcorridor = "PPSPSP"
Output1
Only 2 seats total, adjacent — the single section is forced, so exactly 1 way.

def number_of_ways(corridor):
    MOD = 10**9 + 7
    seats = 0
    ways = 1
    prev_end = -1
    for i, ch in enumerate(corridor):
        if ch != 'S':
            continue
        seats += 1
        if seats % 2 == 1 and seats > 1:
            ways = ways * (i - prev_end) % MOD
        if seats % 2 == 0:
            prev_end = i
    if seats == 0 or seats % 2 == 1:
        return 0
    return ways
function numberOfWays(corridor) {
  const MOD = 1000000007n;
  let seats = 0, prevEnd = -1;
  let ways = 1n;
  for (let i = 0; i < corridor.length; i++) {
    if (corridor[i] !== 'S') continue;
    seats++;
    if (seats % 2 === 1 && seats > 1) {
      ways = (ways * BigInt(i - prevEnd)) % MOD;
    }
    if (seats % 2 === 0) prevEnd = i;
  }
  if (seats === 0 || seats % 2 === 1) return 0;
  return Number(ways);
}
int numberOfWays(String corridor) {
    long MOD = 1_000_000_007L;
    long seats = 0, ways = 1;
    int prevEnd = -1;
    for (int i = 0; i < corridor.length(); i++) {
        if (corridor.charAt(i) != 'S') continue;
        seats++;
        if (seats % 2 == 1 && seats > 1) {
            ways = ways * (i - prevEnd) % MOD;
        }
        if (seats % 2 == 0) prevEnd = i;
    }
    if (seats == 0 || seats % 2 == 1) return 0;
    return (int) ways;
}
int numberOfWays(string corridor) {
    const long long MOD = 1000000007LL;
    long long seats = 0, ways = 1;
    int prevEnd = -1;
    for (int i = 0; i < (int) corridor.size(); i++) {
        if (corridor[i] != 'S') continue;
        seats++;
        if (seats % 2 == 1 && seats > 1) {
            ways = ways * (i - prevEnd) % MOD;
        }
        if (seats % 2 == 0) prevEnd = i;
    }
    if (seats == 0 || seats % 2 == 1) return 0;
    return (int) ways;
}
Time: O(n) Space: O(1)