Number of Ways to Divide a Long Corridor Problem
Description
LeetCode Problem 2147.
Along a long library corridor, there is a line of seats and decorative plants. You are given a 0-indexed string corridor of length n consisting of letters 'S' and 'P' where each 'S' represents a seat and each 'P' represents a plant.
One room divider has already been installed to the left of index 0, and another to the right of index n - 1. Additional room dividers can be installed. For each position between indices i - 1 and i (1 <= i <= n - 1), at most one divider can be installed.
Divide the corridor into non-overlapping sections, where each section has exactly two seats with any number of plants. There may be multiple ways to perform the division. Two ways are different if there is a position with a room divider installed in the first way but not in the second way.
Return the number of ways to divide the corridor. Since the answer may be very large, return it modulo 10^9 + 7. If there is no way, return 0.
Example 1:

Input: corridor = "SSPPSPS"
Output: 3
Explanation: There are 3 different ways to divide the corridor.
The black bars in the above image indicate the two room dividers already installed.
Note that in each of the ways, each section has exactly two seats.
Example 2:

Input: corridor = "PPSPSP"
Output: 1
Explanation: There is only 1 way to divide the corridor, by not installing any additional dividers.
Installing any would create some section that does not have exactly two seats.
Example 3:

Input: corridor = "S"
Output: 0
Explanation: There is no way to divide the corridor because there will always be a section that does not have exactly two seats.
Constraints:
n == corridor.length1 <= n <= 10^5corridor[i]is either'S'or'P'.
Solution
Approach: Memoized Search
Let dfs(i, k) be the number of ways to place dividers from position i onward when the current section already holds k seats. The answer is dfs(0, 0).
- If
iis past the end, the corridor is split correctly only when the last section holds exactly 2 seats, so return1ifk = 2and0otherwise. - If
corridor[i]is a seat, increasek. Ifkbecomes more than 2, return0. - Otherwise we may leave no divider here, giving
dfs(i + 1, k). Ifk = 2, we may also place a divider after positioni, addingdfs(i + 1, 0). Take the sum modulo10^9 + 7.
Complexity: O(n) time and O(n) extra space.
from functools import lru_cache
class Solution:
def numberOfWays(self, corridor: str) -> int:
@lru_cache(None)
def dfs(i: int, k: int) -> int:
if i >= len(corridor):
return int(k == 2)
k += int(corridor[i] == "S")
if k > 2:
return 0
ans = dfs(i + 1, k)
if k == 2:
ans = (ans + dfs(i + 1, 0)) % mod
return ans
mod = 10**9 + 7
ans = dfs(0, 0)
dfs.cache_clear()
return ans