#1931

Painting a Grid With Three Different Colors

Hard
Dynamic ProgrammingDynamic ProgrammingBitmasking
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution uses dynamic programming to efficiently count the valid colorings without generating all combinations. By representing the state of each column with a bitmask, we can keep track of the previous column's colors and ensure adjacent cells are not the same.

⚙️

Algorithm

4 steps
  1. 1Step 1: Define a DP array where dp[i] represents the number of valid ways to color the first i columns.
  2. 2Step 2: Initialize dp[1] with 3 (for the first column).
  3. 3Step 3: For each subsequent column, calculate the number of valid configurations based on the previous column's configurations.
  4. 4Step 4: Use a bitmask to represent the colors of the previous column and ensure no two adjacent cells have the same color.
solution.py11 lines
1# Full working Python code
2MOD = 10**9 + 7
3
4def countWays(m, n):
5    if m == 1:
6        return 3 ** n % MOD
7    dp = [0] * (n + 1)
8    dp[1] = 3
9    for i in range(2, n + 1):
10        dp[i] = dp[i - 1] * 2 % MOD
11    return dp[n]

Complexity note: The time complexity is O(n) because we only iterate through the columns once to compute the number of valid ways to paint them. The space complexity is O(n) due to the DP array storing results for each column.

  • 1Understanding how to represent states using bitmasks can simplify complex problems.
  • 2Dynamic programming can drastically reduce the time complexity of problems that involve counting combinations.

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