#3129

Find All Possible Stable Binary Arrays I

Medium
Dynamic ProgrammingPrefix SumDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n^3)
Space
O(n)
O(n^2)
💡

Intuition

Time O(n^3)Space O(n^2)

Using dynamic programming, we can efficiently count stable binary arrays by building on previously computed results. This avoids the overhead of generating all permutations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define a DP table where dp[a][b][c][d] represents the number of stable arrays with 'a' 0s, 'b' 1s, and 'c' consecutive 0s or 1s at the end, with 'd' indicating if the last added number was a 0 or 1.
  2. 2Step 2: Initialize the DP table with base cases for 0s and 1s.
  3. 3Step 3: Iterate through the DP table and fill it based on the rules of stability, ensuring that no subarray exceeds the limit.
solution.py24 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def countStableBinaryArrays(zero, one, limit):
5    dp = [[[[0 for _ in range(2)] for _ in range(limit + 1)] for _ in range(one + 1)] for _ in range(zero + 1)]
6    dp[0][0][0][0] = 1  # Base case: empty array
7
8    for a in range(zero + 1):
9        for b in range(one + 1):
10            for c in range(limit + 1):
11                for d in range(2):
12                    if d == 0 and a > 0:
13                        dp[a][b][1][0] = (dp[a][b][1][0] + dp[a - 1][b][c][0]) % MOD
14                    if d == 1 and b > 0:
15                        dp[a][b][1][1] = (dp[a][b][1][1] + dp[a][b - 1][c][1]) % MOD
16                    if c < limit:
17                        if d == 0:
18                            dp[a][b][c + 1][0] = (dp[a][b][c + 1][0] + dp[a][b][c][0]) % MOD
19                        else:
20                            dp[a][b][c + 1][1] = (dp[a][b][c + 1][1] + dp[a][b][c][1]) % MOD
21
22    total_count = (dp[zero][one][0][0] + dp[zero][one][0][1]) % MOD
23    return total_count
24

Complexity note: The time complexity is O(n^3) due to the nested loops iterating through the counts of 0s, 1s, and the limit. The space complexity is O(n^2) for storing the DP table.

  • 1Dynamic programming can significantly reduce the complexity of counting problems.
  • 2Understanding the constraints of the problem helps in designing efficient algorithms.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.