Number of Ways to Paint N × 3 Grid Problem
Description
LeetCode Problem 1411.
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 10^9 + 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.length1 <= n <= 5000
Solution
Approach: Two Kinds of Rows
A single row of three cells can be painted in 12 ways, and they come in two kinds:
- two colors, like
aba(the ends share a color): 3 · 2 = 6 rows, - three colors, like
abc: 3 · 2 · 1 = 6 rows.
How many rows can go below a given row depends only on its kind, not on the actual colors. Working through one example of each (say RYR and RYG):
- below a two-color row fit 5 rows: 3 of the two-color kind and 2 of the three-color kind;
- below a three-color row fit 4 rows: 2 of each kind.
So if two and three count the paintings whose last row is of each kind, adding one row gives:
two' = 3 · two + 2 · threethree' = 2 · two + 2 · three
Start from two = three = 6 for one row, apply the step n − 1 times, and return two + three, everything modulo 10^9 + 7. The intermediate value 3 · two + 2 · three can be up to about 5 · 10^9, so it needs 64-bit integers in Java, C++ and Go.
Complexity: O(n) time and O(1) space.
class Solution:
def numOfWays(self, n: int) -> int:
mod = 10**9 + 7
two, three = 6, 6 # rows like "aba" (two colors) and "abc" (three colors)
for _ in range(n - 1):
two, three = (3 * two + 2 * three) % mod, (2 * two + 2 * three) % mod
return (two + three) % mod