AlgoInsight

DSA problem

Number of Ways to Paint N × 3 Grid

Hard1-D DPPattern: 1-D DPtop600GoogleAmazonMicrosoftBloombergApple

You have a grid with n rows and 3 columns. Each cell must be painted Red, Yellow, or Green such that no two adjacent cells share the same color (horizontally within a row, or vertically between rows). Given an integer n, return the number of ways to paint the grid. Since the answer may be very large, return it modulo 10^9 + 7.

The trick is to classify every valid row into exactly one of two structural categories:

Now ask: given a row of type ABA, how many valid rows of each type can follow it directly below? A careful enumeration shows: 3 next-row ABA patterns are compatible, and 2 next-row ABC patterns are compatible. Similarly, after an ABC row: 2 next ABA patterns and 2 next ABC patterns are compatible.

This gives a tiny 2-state linear recurrence — pure 1-D DP. Let aba = number of ways to paint a valid grid of i rows whose last row is ABA-type, and abc analogously. Then:

aba_new = 3 * aba + 2 * abc abc_new = 2 * aba + 2 * abc

with the base case aba = 6 and abc = 6 (the count of valid 1-row grids of each type). Iterate n - 1 more times and return (aba + abc) mod (10^9 + 7). The whole solution is O(n) time and O(1) space.

Examples

Example 1
Input: n = 1
Output: 12
Explanation: There are 6 ABA-type rows and 6 ABC-type rows, totalling 12 valid 1-row grids.
Example 2
Input: n = 2
Output: 54
Explanation: Each ABA row leads to 3 ABA + 2 ABC = 5 next rows; each ABC leads to 2 + 2 = 4 next rows. Total = 6*5 + 6*4 = 30 + 24 = 54.
Example 3
Input: n = 5000
Output: 30228214
Explanation: Apply the recurrence 4999 times modulo 10^9 + 7 to obtain the result.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dp1d-dpmathcombinatorics

Browse all DSA problems