We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Number of Ways to Divide a Long Corridor

Difficulty: Hard


Problem Description

Given a string corridor consisting of letters 'S' (seats) and 'P' (plants), determine the number of ways to divide the corridor into non-overlapping sections, where each section has exactly two seats. Return the number of ways modulo 10^9 + 7. If no valid divisions exist, return 0.


Key Insights

  • Each section must contain exactly two 'S' characters.
  • The number of 'S' characters must be even for any divisions to be possible.
  • The sections can be separated by installing dividers at positions between 'S' characters.
  • The number of ways to install dividers is determined by the gaps between the pairs of 'S'.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

To solve the problem, we can follow these steps:

  1. Count 'S' Characters: Traverse the string to count the number of 'S'. If the count is odd, return 0 immediately.
  2. Identify Positions of 'S': Store the indices of all 'S' characters in a list for easier access.
  3. Calculate the Number of Ways:
    • Group the 'S' into pairs.
    • For each pair of 'S', calculate the number of ways to place dividers based on the gaps between the pairs.
    • The number of gaps between each pair of 'S' can be used to calculate combinations.
  4. Return Result: Use modular arithmetic to return the result.

Code Solutions

def numberOfWays(corridor: str) -> int:
    MOD = 10**9 + 7
    s_indices = [i for i, c in enumerate(corridor) if c == 'S']
    s_count = len(s_indices)

    # If the number of seats is odd, return 0
    if s_count % 2 != 0:
        return 0

    # Calculate the number of ways to place dividers
    ways = 1
    for i in range(2, s_count, 2):
        gap = s_indices[i] - s_indices[i - 2] - 1
        ways = (ways * (gap + 1)) % MOD

    return ways
← Back to All Questions