LeetCode Entry

2147. Number of Ways to Divide a Long Corridor

14.12.2025 hard 2025 kotlin rust

Ways to split pairs of S

2147. Number of Ways to Divide a Long Corridor hard blog post substack youtube

895a38fb-0bef-4120-80b5-a786aa620ac5 (1).webp

Join me on Telegram

https://t.me/leetcode_daily_unstoppable/1204

Problem TLDR

Ways to split pairs of S #hard

Intuition

    // p p s p p s p p

Chunk by pairs of ‘s’, multiply counts of in-between ‘p’.

Approach

  • or, rearrange the problem and add the accumulated value on each new ‘p’

Complexity

  • Time complexity: \(O(n)\)

  • Space complexity: \(O(1)\)

Code

// 34ms
    fun numberOfWays(c: String): Int {
        var a = 0; var b = 1; var s = 1
        for (c in c) if (c == 'P') b = (a * (s%2) + b) % 1000000007
            else if (++s%2>0) a = b
        return a * (s%2)
    }
// 3ms
    pub fn number_of_ways(c: String) -> i32 {
        let (mut a, mut b, mut even) = (0, 1, true);
        for c in c.as_bytes().chunk_by(|x, y| x == y) {
            if c[0] == b'P' {
                if even && a > 0 { b = (b + c.len()* a) % 1_000_000_007 }
            } else {
                if !even || c.len() > 1 { a = b }
                if c.len() & 1 > 0 { even = !even }
            }
        } even as i32 * a as i32
    }