Number of Ways to Paint N × 3 Grid - Problem

You have a grid of size n × 3 and you want to paint each cell of the grid with exactly one of the three colors: Red, Yellow, or Green.

The constraint is that no two adjacent cells can 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.

Input & Output

Example 1 — Single Row
$ Input: n = 1
Output: 12
💡 Note: For a 1×3 grid, we have 3 choices for first cell, 2 for second (different from first), and 2 for third (different from second). However, we need to consider both ABA patterns (6 ways) and ABC patterns (6 ways), giving total 12 ways.
Example 2 — Two Rows
$ Input: n = 2
Output: 54
💡 Note: Starting with 12 ways for first row (6 ABA + 6 ABC), each pattern can transition to valid patterns in the second row based on transition rules.
Example 3 — Three Rows
$ Input: n = 3
Output: 246
💡 Note: Each additional row multiplies the possibilities based on valid color transitions from the previous row patterns.

Constraints

  • 1 ≤ n ≤ 5000

Visualization

Tap to expand
Number of Ways to Paint N × 3 Grid INPUT N × 3 Grid (n = 1) ? ? ? Available Colors: Red Yellow Green Constraint: No adjacent cells can have the same color n = 1 mod = 10^9 + 7 ALGORITHM STEPS (DP) 1 Classify Patterns ABC type (3 colors): 12 ways ABA type (2 colors): 6 ways 2 Define DP States abc[i] = ABC patterns at row i aba[i] = ABA patterns at row i 3 Transition Formula abc[i] = 2*abc[i-1] + 2*aba[i-1] aba[i] = 2*abc[i-1] + 3*aba[i-1] 4 Base Case (n=1) abc[1] = 6, aba[1] = 6 Total = 6 + 6 = 12 Sample Valid Patterns: ABC ABA Result = (abc[n] + aba[n]) % MOD FINAL RESULT All 12 Valid Colorings: 6 ABC-type + 6 ABA-type = 12 Calculation (n=1): abc[1] = 6 aba[1] = 6 Total = 6 + 6 = 12 OUTPUT 12 OK Key Insight: For a 3-column row, valid patterns are either ABC-type (3 different colors) or ABA-type (first and last same). Use DP to track how many of each type exist at each row. Transitions depend on which patterns from row i-1 can lead to valid ABC or ABA patterns at row i. Time: O(n), Space: O(1) with optimized DP. TutorialsPoint - Number of Ways to Paint N × 3 Grid | Dynamic Programming Approach
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
28.4K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen