#2147
Number of Ways to Divide a Long Corridor
HardMathStringDynamic ProgrammingDynamic ProgrammingCombinatorial Counting
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
By counting the number of 'S' and ensuring they can be grouped into pairs, we can calculate the number of ways to place dividers more efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Count the total number of 'S' in the corridor.
- 2Step 2: If the count of 'S' is odd or less than 2, return 0 as we can't form pairs.
- 3Step 3: Calculate the number of pairs of 'S' and the number of plants in between them.
- 4Step 4: Use combinatorial mathematics to calculate the number of ways to place dividers.
solution.py9 lines
1def countWays(corridor):
2 mod = 10**9 + 7
3 seats = [i for i, c in enumerate(corridor) if c == 'S']
4 if len(seats) % 2 != 0:
5 return 0
6 ways = 1
7 for i in range(1, len(seats) // 2):
8 ways = (ways * (seats[2 * i] - seats[2 * i - 1])) % mod
9 return waysℹ
Complexity note: This complexity is linear because we only traverse the string a couple of times and store the indices of 'S'.
- 1The number of 'S' must be even to form pairs.
- 2The spaces between pairs of 'S' determine the number of valid configurations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.