Description
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.length1 <= n <= 5000
Solutions
This solution uses dynamic programming built on a key insight: any valid coloring of a single 3-cell row falls into one of two shapes — an ABA pattern (the two outer cells share a color, like Red-Yellow-Red) or an ABC pattern (all three cells differ), and there are exactly 6 of each for the first row, giving the starting values A = 6 and B = 6. Counting how one row can sit on top of another shows that a row below an ABA row can be one of 3 ABA + 2 ABC patterns, while a row below an ABC row allows 2 of each — which yields the recurrences newA = 2 * A + 2 * B and newB = 2 * A + 3 * B. The loop applies these transitions once per additional row, keeping every value reduced modulo 10^9 + 7 to avoid overflow, and the final answer is simply (A + B) % MOD. By tracking only two aggregate counts instead of enumerating actual grids, it runs in O(n) time with O(1) memory — a massive improvement over the exponential backtracking approach.
/**
* @param {number} n
* @return {number}
*/
var numOfWays = function(n) {
const MOD = 10 ** 9 + 7;
let A = 6;
let B = 6;
for (let i = 2; i <= n; i++) {
const newA = (2 * A + 2 * B) % MOD;
const newB = (2 * A + 3 * B) % MOD;
A = newA;
B = newB;
}
return (A + B) % MOD;
};