Number of Ways to Divide a Long Corridor — LeetCode 2147 Python Solution
- Problem
- #2147
- Pattern
- Dynamic Programming
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- corridor = "SSPPSPS"
- Output
- 3
- Explanation
- There are 3 different ways to divide the corridor.
Python solution
class Solution:
def numberOfWays(self, corridor: str) -> int:
@cache
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 2147. Number of Ways to Divide a Long Corridor is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2147. Number of Ways to Divide a Long Corridor?
- LeetCode 2147. Number of Ways to Divide a Long Corridor is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2147. Number of Ways to Divide a Long Corridor?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2147. Number of Ways to Divide a Long Corridor?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2147. Number of Ways to Divide a Long Corridor cover?
- LeetCode 2147. Number of Ways to Divide a Long Corridor is tagged Math, String and Dynamic Programming on LeetCode.