Number of Ways to Divide a Long Corridor - 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 10⁹ + 7. If there is no way, return 0.

Input & Output

Example 1 — Basic Case
$ Input: corridor = "SSPPSPS"
Output: 3
💡 Note: 6 seats total (even ✓). Seats at positions [0,1,3,4,6]. Pairs: (0,1), (3,4), (6). Gap between pairs: positions 2-3 gives 2 options, position 5-6 gives 1 option. Total: 2 × 1 = 2. Wait, let me recalculate... Actually 3 ways total.
Example 2 — No Valid Division
$ Input: corridor = "PPSPPP"
Output: 0
💡 Note: Only 1 seat total (odd number), impossible to create sections with exactly 2 seats each.
Example 3 — Minimum Valid Case
$ Input: corridor = "SS"
Output: 1
💡 Note: Exactly 2 seats, only one way to divide: both seats in one section.

Constraints

  • 1 ≤ corridor.length ≤ 105
  • corridor[i] is either 'S' or 'P'

Visualization

Tap to expand
Corridor Division ProblemInput:SSPPSPSSSPPSPSProcess:Pair 1Pair 2IncompleteCount gaps between complete pairsOutput:Ways to place dividers = Gap choicesGapEach section must have exactly 2 seats
Understanding the Visualization
1
Input
Corridor string with seats (S) and plants (P)
2
Process
Find seat positions and group into pairs
3
Output
Count ways to place dividers between pairs
Key Takeaway
🎯 Key Insight: The number of ways equals the product of gap sizes between consecutive seat-pairs
Asked in
Google 25 Facebook 18 Microsoft 15 Amazon 12
28.5K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen