Skip to content

1527. Number Of Ways To Paint N 3 Grid

Dynamic Programming

Problem - Number Of Ways To Paint N 3 Grid

Hard

You have a grid of size n x 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green while making sure that no two adjacent cells have the same color (i.e., no two cells that share vertical or horizontal sides have the same color).

Given n the number of rows of the grid, return the number of ways you can paint this grid. As the answer may grow large, the answer must be computed modulo 109 + 7.

 

Example 1:

Input: n = 1
Output: 12
Explanation: There are 12 possible way to paint the grid as shown.

Example 2:

Input: n = 5000
Output: 30228214

 

Constraints:

  • n == grid.length
  • 1 <= n <= 5000

Solutions

1
2
3
4
5
6
7
8
9
class Solution:
    def numOfWays(self, n: int) -> int:
        mod = 10**9 + 7
        count2 = count3 = 6
        for _ in range(n - 1):
            last2, last3 = count2, count3
            count2 = (3 * last2 + 2 * last3) % mod
            count3 = (2 * last2 + 2 * last3) % mod
        return (count2 + count3) % mod

Submission Stats:

  • Runtime: 7 ms (83.84%)
  • Memory: 17.2 MB (96.04%)