Leetcode #2147: Number of Ways to Divide a Long Corridor
In this guide, we solve Leetcode #2147 Number of Ways to Divide a Long Corridor in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Math, String, Dynamic Programming
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
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.
Python Solution
class Solution:
def numberOfWays(self, corridor: str) -> int:
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
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.