LeetCode 2147: Number of Ways to Divide a Long Corridor Solution

Master LeetCode problem 2147 (Number of Ways to Divide a Long Corridor), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2147. Number of Ways to Divide a Long Corridor

Problem Explanation

Explanation:

To solve this problem, we can iterate through the corridor and count the number of ways to divide the corridor at each position. We can keep track of the number of seats and plants encountered so far. If the current position is a seat, we can calculate the number of ways based on the number of seats and plants encountered so far.

At each position, we can have the following scenarios:

  1. Two seats encountered: We can place a divider to create a section with two seats and any number of plants in between.
  2. One seat and one plant encountered: We can place a divider to create a section with two seats and the plant in between.
  3. Two plants encountered: We cannot place a divider as there must be exactly two seats in each section.

We can use dynamic programming to keep track of the number of ways at each position and calculate the final result modulo 10^9 + 7.

Time Complexity: The time complexity of this approach is O(n) where n is the length of the corridor.

Space Complexity: The space complexity is O(1) as we are only using a constant amount of extra space.

:

Solution Code

class Solution {
    public int waysToDivide(String corridor) {
        long MOD = 1000000007;
        int n = corridor.length();
        long ways = 0;
        int seats = 0, plants = 0;

        for (int i = 0; i < n; i++) {
            if (corridor.charAt(i) == 'S') {
                seats++;
            } else {
                plants++;
            }

            if (seats >= 2 && plants >= 1) {
                ways = (ways + Math.min(seats - 1, plants)) % MOD;
            }
        }

        return (int) ways;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2147 (Number of Ways to Divide a Long Corridor)?

This page provides optimized solutions for LeetCode problem 2147 (Number of Ways to Divide a Long Corridor) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2147 (Number of Ways to Divide a Long Corridor)?

The time complexity for LeetCode 2147 (Number of Ways to Divide a Long Corridor) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2147 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2147 in Java, C++, or Python.

Back to LeetCode Solutions