Number of Ways to Divide a Long Corridor solution and explanation
9 more videos on this problem
Number of Ways to Divide a Long Corridor | Clear Intuition | Dry Run | Leetcode 2147 | MIKcodestorywithMIK · 23:58 · 9K views
Number of Ways to Divide a Long Corridor - Leetcode 2147 - PythonNeetCodeIO · 21:56 · 7K views
Number of Ways to Divide a Long Corridor| Leetcode 2147| Complete Intuition Explained Sanyam IIT Guwahati · 14:07 · 1K views
Daily Leetcode #2084: Dec 14, 2025 - 2147. Number of Ways to Divide a Long CorridorProgramming Live with Larry · 12:35 · 589 views
Number of Ways to Divide a Long Corridor | LeetCode 2147 🔥 | DCC | Counting | Optimal Approach Study Placement · 17:21 · 544 views
2147. Number of Ways to Divide a Long Corridor (Leetcode Hard)Programming Live with Larry · 17:17 · 441 views
2147. Number of Ways to Divide a Long Corridor | Leetcode Daily - PythonLeetcode Daily · 9:37 · 358 views
Number of Ways to Divide a Long Corridor | LeetCode 2147 - Pythonimpoldev · 9:49 · 189 views
Leetcode 2147 Number of Ways to Divide a Long CorridorThinkCode · 8:30 · 157 views
LeetCode Daily 2147 | Number of Ways to Divide a Long Corridor | Hard | Solution WalkthroughDaily Dose Of LeetCode · 20:14 · 129 views
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.
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 109 + 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 <= 105corridor[i]is either'S'or'P'.
Approach overview
Problem Overview: You get a corridor represented by a string containing seats (S) and plants (P). The corridor must be divided using partitions so every section contains exactly two seats. The task is to count how many valid ways you can place these dividers.
Approach 1: Counting Seats and Calculating Divisions (O(n) time, O(1) space)
Scan the corridor and group seats in pairs. Each valid section must contain exactly two seats, so the structure becomes fixed once you locate seat positions. After the first pair is completed, count the number of plants between the second seat of the previous pair and the first seat of the next pair. Every plant position between those pairs becomes a potential divider location, so multiply the number of choices for each gap. This produces a running product of valid partition placements. The approach behaves like lightweight dynamic programming because the total number of arrangements accumulates as you process the string.
Approach 2: Two-Pointer Technique (O(n) time, O(1) space)
Use two pointers to locate seat pairs directly. Move the right pointer until two seats are found, marking the end of a section. Then advance the pointer across plants until the next seat appears. The number of plants skipped determines how many divider positions exist between seat pairs. Multiply this count into the answer and repeat until the corridor ends. This pointer-based traversal avoids extra storage and keeps the logic simple while still processing the string in one pass.
Recommended for interviews: The seat-counting multiplication approach is the most common solution. It demonstrates understanding of pattern observation and linear scanning over a string. Interviewers expect the O(n) solution using combinatorial counting from math. A brute-force attempt that tries every partition quickly becomes exponential and is mainly useful to reason about why counting gaps works.
Approach 1: Counting Seats and Calculating Divisions
This approach involves counting the total number of 'S' in the string. We need to ensure that the total number of seats is even, as every section must have exactly two seats. If the count of 'S' is not even or less than two, return 0 because no valid sections can be formed.
Initialize a counter for seats and iterate through the corridor. Each time you encounter the second seat in a pair, check how many plants were between this second seat and the previous pair of seats. The count of positions (plants) between these pairs is the spot where dividers can be placed. Compute the total number of ways combine these choices.
def number_of_ways(corridor):
MOD = 10**9 + 7
seat_count = 0
for c in corridor:
if c == 'S':
seat_count += 1
if seat_count % 2 != 0 or seat_count < 2:
return 0
ways = 1
plants_between_seats = 0
found_first_pair = False
current_seats = 0
for c in corridor:
if c == 'S':
current_seats += 1
if current_seats == 2:
if found_first_pair:
ways = (ways * (plants_between_seats + 1)) % MOD
plants_between_seats = 0
found_first_pair = True
current_seats = 0
elif found_first_pair:
plants_between_seats += 1
return waysfunction numberOfWays(corridor) {
const MOD = 1e9 + 7;
let seatCount = 0;
for (let char of corridor) {
if (char === 'S') seatCount++;
}
if (seatCount % 2 !== 0 || seatCount < 2) return 0;
let ways = 1,
plantsBetween = 0,
foundFirstPair = false,
currentSeats = 0;
for (let char of corridor) {
if (char === 'S') {
currentSeats++;
if (currentSeats === 2) {
if (foundFirstPair) {
ways = (ways * (plantsBetween + 1)) % MOD;
}
plantsBetween = 0;
foundFirstPair = true;
currentSeats = 0;
}
} else if (foundFirstPair) {
plantsBetween++;
}
}
return ways;
}This implementation first counts all 'S' in the corridor to determine if it's possible to split the corridor. It then iterates through the string, calculates how many plants ('P') are between every two pairs of seats ('S'), and uses this count to determine the number of ways dividers can be placed.
Time Complexity: O(n), where n is the length of the corridor string because it processes the string in a single pass.
Space Complexity: O(1), since it uses a fixed amount of extra space for variables.
Approach 2: Two-Pointer Technique
The two-pointer technique helps efficiently track the segments of the corridor. Position both pointers initially at the start of the string. Move the first pointer until two 'S' characters are found, marking the start of a section. Move the second pointer to continue finding the next two 'S' for another section.
Each transition between segments of groups discovered by the pointers represents a potential divider placement, and the number of these potential movements gives the number of possible configurations.
public class CorridorDivider {
public int numberOfWays(String corridor) {
final int MOD = 1000000007;
int seatCount = 0;
for (char c : corridor.toCharArray()) {
if (c == 'S') seatCount++;
}
if (seatCount % 2 != 0 || seatCount < 2) return 0;
int ways = 1;
int plantsBetween = 0;
boolean firstPairFound = false;
int currentSeats = 0;
for (char c : corridor.toCharArray()) {
if (c == 'S') {
currentSeats++;
if (currentSeats == 2) {
if (firstPairFound) {
ways = (int)(((long)ways * (plantsBetween + 1)) % MOD);
}
plantsBetween = 0;
firstPairFound = true;
currentSeats = 0;
}
} else if (firstPairFound) {
plantsBetween++;
}
}
return ways;
}
public static void main(String[] args) {
CorridorDivider cd = new CorridorDivider();
System.out.println(cd.numberOfWays("SSPPSPS"));
}
}#include <iostream>
#include <string>
int numberOfWays(const std::string& corridor) {
const int MOD = 1e9 + 7;
int seat_count = 0;
for (char c : corridor) {
if (c == 'S') seat_count++;
}
if (seat_count % 2 != 0 || seat_count < 2) return 0;
int ways = 1, plants_between = 0;
bool first_pair_found = false;
int current_seats = 0;
for (char c : corridor) {
if (c == 'S') {
current_seats++;
if (current_seats == 2) {
if (first_pair_found) {
ways = static_cast<long long>(ways) * (plants_between + 1) % MOD;
}
plants_between = 0;
first_pair_found = true;
current_seats = 0;
}
} else if (first_pair_found) {
plants_between++;
}
}
return ways;
}
int main() {
std::string corridor = "SSPPSPS";
std::cout << numberOfWays(corridor) << std::endl;
return 0;
}The Java solution leverages the same principle of scanning and counting, using long for the multiplication to avoid overflow and mod to control large numbers.
Time Complexity: O(n), iterating through the corridor string once.
Space Complexity: O(1), due to a constant number of helper variables.
Approach 3: Memoization Search
We design a function dfs(i, k), which represents the number of ways to partition the corridor at the i-th position, having already placed k screens. Then the answer is dfs(0, 0).
The calculation process of the function dfs(i, k) is as follows:
If i geq len(corridor), it means the corridor has been fully traversed. At this point, if k = 2, it indicates that a valid partitioning scheme has been found, so return 1. Otherwise, return 0.
Otherwise, we need to consider the situation at the current position i:
- If
corridor[i] = 'S', it means the current position is a seat, and we incrementkby1. - If
k > 2, it means the number of screens placed at the current position exceeds2, so return0. - Otherwise, we can choose not to place a screen, i.e.,
dfs(i + 1, k). Ifk = 2, we can also choose to place a screen, i.e.,dfs(i + 1, 0). We add the results of these two cases and take the result modulo10^9 + 7, i.e.,ans = (ans + dfs(i + 1, k)) bmod mod.
Finally, we return dfs(0, 0).
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the corridor.
function numberOfWays(corridor: string): number {
const n = corridor.length;
const mod = 10 ** 9 + 7;
const f: number[][] = Array.from({ length: n }, () => Array(3).fill(-1));
const dfs = (i: number, k: number): number => {
if (i >= n) {
return k === 2 ? 1 : 0;
}
if (f[i][k] !== -1) {
return f[i][k];
}
if (corridor[i] === 'S') {
++k;
}
if (k > 2) {
return (f[i][k] = 0);
}
f[i][k] = dfs(i + 1, k);
if (k === 2) {
f[i][k] = (f[i][k] + dfs(i + 1, 0)) % mod;
}
return f[i][k];
};
return dfs(0, 0);
}func numberOfWays(corridor string) int {
n := len(corridor)
f := make([][3]int, n)
for i := range f {
f[i] = [3]int{-1, -1, -1}
}
const mod = 1e9 + 7
var dfs func(int, int) int
dfs = func(i, k int) int {
if i >= n {
if k == 2 {
return 1
}
return 0
}
if f[i][k] != -1 {
return f[i][k]
}
if corridor[i] == 'S' {
k++
}
if k > 2 {
return 0
}
f[i][k] = dfs(i+1, k)
if k == 2 {
f[i][k] = (f[i][k] + dfs(i+1, 0)) % mod
}
return f[i][k]
}
return dfs(0, 0)
}impl Solution {
pub fn number_of_ways(corridor: String) -> i32 {
let n: usize = corridor.len();
let bytes = corridor.as_bytes();
let modv: i32 = 1_000_000_007;
let mut f = vec![vec![-1; 3]; n];
fn dfs(
i: usize,
k: usize,
n: usize,
bytes: &[u8],
f: &mut Vec<Vec<i32>>,
modv: i32,
) -> i32 {
if i >= n {
return if k == 2 { 1 } else { 0 };
}
if f[i][k] != -1 {
return f[i][k];
}
let mut nk = k;
if bytes[i] == b'S' {
nk += 1;
}
if nk > 2 {
return 0;
}
let mut res = dfs(i + 1, nk, n, bytes, f, modv);
if nk == 2 {
res = (res + dfs(i + 1, 0, n, bytes, f, modv)) % modv;
}
f[i][k] = res;
res
}
dfs(0, 0, n, bytes, &mut f, modv)
}
}Approach 4: Mathematics
We can divide every two seats into a group. Between two adjacent groups of seats, if the distance between the last seat of the previous group and the first seat of the next group is x, then there are x ways to place the screen.
We traverse the corridor, using a variable cnt to record the current number of seats, and a variable last to record the position of the last seat.
When we encounter a seat, we increment cnt by 1. If cnt is greater than 2 and cnt is odd, then we need to place a screen between last and the current seat. The number of ways to do this is ans times (i - last), where ans is the previous number of ways. Then, we update last to the current seat's position i.
Finally, if cnt is greater than 0 and cnt is even, return ans; otherwise, return 0.
The time complexity is O(n), where n is the length of the corridor. The space complexity is O(1).
function numberOfWays(corridor: string): number {
const mod = 10 ** 9 + 7;
const n = corridor.length;
let [ans, cnt, last] = [1, 0, 0];
for (let i = 0; i < n; ++i) {
if (corridor[i] === 'S') {
if (++cnt > 2 && cnt % 2) {
ans = (ans * (i - last)) % mod;
}
last = i;
}
}
return cnt > 0 && cnt % 2 === 0 ? ans : 0;
}func numberOfWays(corridor string) int {
const mod int = 1e9 + 7
ans, cnt, last := 1, 0, 0
for i, c := range corridor {
if c == 'S' {
cnt++
if cnt > 2 && cnt%2 == 1 {
ans = ans * (i - last) % mod
}
last = i
}
}
if cnt > 0 && cnt%2 == 0 {
return ans
}
return 0
}impl Solution {
pub fn number_of_ways(corridor: String) -> i32 {
let modv: i64 = 1_000_000_007;
let mut ans: i64 = 1;
let mut cnt: i64 = 0;
let mut last: i64 = 0;
for (i, ch) in corridor.chars().enumerate() {
if ch == 'S' {
cnt += 1;
if cnt > 2 && cnt % 2 == 1 {
ans = ans * (i as i64 - last) % modv;
}
last = i as i64;
}
}
if cnt > 0 && cnt % 2 == 0 {
ans as i32
} else {
0
}
}
}Complexity comparison
| Approach | Complexity |
|---|---|
| Counting Seats and Calculating Divisions | Time Complexity: O(n), where n is the length of the corridor string because it processes the string in a single pass. Space Complexity: O(1), since it uses a fixed amount of extra space for variables. |
| Two-Pointer Technique | Time Complexity: O(n), iterating through the corridor string once. Space Complexity: O(1), due to a constant number of helper variables. |
| Memoization Search | – |
| Mathematics | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Counting Seats and Calculating Divisions | O(n) | O(1) | Best general solution; simple linear scan and multiplication of valid divider positions |
| Two-Pointer Technique | O(n) | O(1) | Useful when explicitly tracking seat boundaries while scanning the corridor |
Frequently asked questions
Is Number of Ways to Divide a Long Corridor easy or hard?
The problem is labeled Hard because the counting insight is not immediately obvious. Once you recognize that divider positions depend on plants between seat pairs, the implementation becomes a straightforward O(n) linear scan.
Number of Ways to Divide a Long Corridor Python/Java solution
Python, Java, C++, and JavaScript implementations all follow the same logic: scan the corridor, detect seat pairs, count plants between pairs, and multiply the number of valid divider positions. Each implementation runs in O(n) time with constant extra space.
How to solve Number of Ways to Divide a Long Corridor in O(n)?
Iterate through the string while counting seats. Every time two seats form a section, track the number of plants until the next seat appears. The number of plants plus one represents the possible divider positions between seat groups, and multiplying these values gives the final count.
What is the best approach for Number of Ways to Divide a Long Corridor?
The best approach scans the corridor once, groups seats into pairs, and multiplies the number of divider positions between seat pairs. Each gap between consecutive seat pairs may contain several plants, and each plant position represents a valid place for a divider. This produces an O(n) time and O(1) space solution.
Is Number of Ways to Divide a Long Corridor asked at Google/Amazon/Meta?
This problem follows patterns commonly asked by companies like Google, Amazon, and Meta because it combines string traversal, combinatorial counting, and pattern recognition. Similar counting and partitioning problems appear frequently in technical interviews.
What data structure is used in Number of Ways to Divide a Long Corridor?
The solution mainly relies on string traversal and integer counters. No complex data structures are required; the algorithm tracks seat counts and multiplies gap sizes while scanning the string.
What is the time complexity of Number of Ways to Divide a Long Corridor?
The optimal solution runs in O(n) time because the corridor string is scanned once while counting seats and plants between seat pairs. Only constant additional variables are required, so the space complexity is O(1).
