Number of Ways to Divide a Long Corridor

Hard · 1-D Dynamic Programming · Explanation and code example

Combinatorics (Optimal)

How it works

We can optimize the combinatorics approach by not storing all seat positions. Instead, we track the count of seats and the position of the previous seat. Whenever we complete a pair (seat count becomes even and greater than 2), we multiply by the gap between the current seat and the previous one.

Steps

  1. Initialize count = 0, res = 1, and prev = -1 to track the position of the last seat.
  2. Iterate through the corridor:
    • When a seat is found, increment count.
    • If count > 2 and count % 2 == 1 (meaning we just started a new section), multiply res by the distance from prev.
    • Update prev to the current position.
  3. If count >= 2 and count % 2 == 0, return res; otherwise return 0.

Complexity

  • Time complexity: O(n)
  • Space complexity: O(1)

Things to watch for

Not Handling Edge Cases for Seat Count

If the total number of seats is odd or less than 2, there is no valid way to divide the corridor. Forgetting to check these conditions at the start leads to incorrect results or division by zero errors when computing gap products.

Misunderstanding Where Dividers Can Be Placed

Dividers can only be placed between sections, specifically in the gaps between the second seat of one section and the first seat of the next section. The number of valid positions for each divider equals the number of positions between consecutive seat pairs (the gap includes all plants plus the implicit space between seats).

Off-by-One Errors in Gap Calculation

The gap between the 2nd seat of one section and the 1st seat of the next is seats[i+1] - seats[i], not seats[i+1] - seats[i] - 1 or seats[i+1] - seats[i] + 1. This represents the number of possible divider positions, including placing it immediately after the 2nd seat.

Forgetting to Apply Modulo During Multiplication

The product of gaps can become extremely large. Applying modulo only at the end causes integer overflow. You must apply modulo after each multiplication step to keep the intermediate results within bounds.

Incorrect Loop Bounds in Combinatorics Approach

When iterating through seat positions to compute gap products, the loop should process pairs (seats[1], seats[2]), (seats[3], seats[4]), etc. Starting at the wrong index or using incorrect step sizes skips gaps or includes invalid pairs.

Python code example

class Solution:
    def numberOfWays(self, corridor: str) -> int:
        mod = 1_000_000_007
        count = 0
        res = 1
        prev = -1

        for i, c in enumerate(corridor):
            if c == 'S':
                count += 1
                if count > 2 and count % 2 == 1:
                    res = (res * (i - prev)) % mod
                prev = i

        return res if count >= 2 and count % 2 == 0 else 0

C++ code example

class Solution {
public:
    int numberOfWays(string corridor) {
        int mod = 1'000'000'007, count = 0, res = 1, prev = -1;

        for (int i = 0; i < corridor.size(); i++) {
            if (corridor[i] == 'S') {
                count++;
                if (count > 2 && count % 2 == 1) {
                    res = (1LL * res * (i - prev)) % mod;
                }
                prev = i;
            }
        }

        return (count >= 2 && count % 2 == 0) ? res : 0;
    }
};
Source and license

Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.

Your recall check is in progress. Write your attempt before revealing the explanation.

Resume recall check

Browse all problem explanations