Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created December 14, 2025 18:44
Show Gist options
  • Select an option

  • Save tatsuyax25/6026e23a8a5ad4fcb792ff0f7927b5b2 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/6026e23a8a5ad4fcb792ff0f7927b5b2 to your computer and use it in GitHub Desktop.
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
/**
* Calculates the number of ways to divide a corridor into valid sections.
* Each section must contain exactly two 'S' (seats).
* 'P' (plants) between pairs of seats determine possible partitions.
*
* @param {string} corridor - A string consisting of 'S' (seats) and 'P' (plants).
* @return {number} - The number of valid ways to divide the corridor.
*/
var numberOfWays = function(corridor) {
const MOD = 1e9 + 7; // Large prime modulus to prevent overflow
let product = 1; // Final result (multiplicative accumulation of choices)
let seatCount = 0; // Tracks how many seats ('S') have been seen
let plantCount = 0; // Tracks plants ('P') between pairs of seats
// Traverse the corridor string
for (let i = 0; i < corridor.length; i++) {
const char = corridor[i];
// Count seats
if (char === 'S') {
seatCount++;
}
// Count plants only when we are between exactly two seats
if (seatCount === 2 && char === 'P') {
plantCount++;
}
// When we encounter the 3rd seat:
// - We close off the previous section (which had 2 seats).
// - The number of ways to partition depends on how many plants were in between.
// - Reset plantCount and continue with the next section.
if (seatCount === 3) {
product = (product * (plantCount + 1)) % MOD;
plantCount = 0;
seatCount = 1; // Carry over the last seat to start the next section
}
}
// If fewer than 2 seats exist, no valid partition is possible
if (seatCount < 2) {
return 0;
}
return product;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment