Number of Ways to Paint N × 3 Grid - Problem

Imagine you're tasked with creating a stunning n × 3 grid art piece using exactly three colors: Red, Yellow, and Green. The challenge? No two adjacent cells can share the same color!

Each cell in your grid must be painted with exactly one color, and cells that share a horizontal or vertical edge cannot have the same color. This creates a beautiful constraint that makes the problem both challenging and elegant.

Your mission: Given n (the number of rows), calculate how many different ways you can paint this grid while following the adjacency rule.

Note: Since the answer can grow exponentially large, return the result modulo 109 + 7.

Input & Output

example_1.py — Basic Case
$ Input: n = 1
Output: 12
💡 Note: For a 1×3 grid, we have 6 ABA patterns (RGR, RYR, GRG, GYG, YRY, YGY) and 6 ABC patterns (RGY, RYG, GRY, GYR, YRG, YGR), totaling 12 ways.
example_2.py — Small Grid
$ Input: n = 2
Output: 54
💡 Note: For a 2×3 grid, we apply transition rules: from 6 ABA + 6 ABC in first row, we get (6×3 + 6×2) + (6×2 + 6×2) = 30 + 24 = 54 total ways.
example_3.py — Larger Grid
$ Input: n = 3
Output: 246
💡 Note: For a 3×3 grid, continuing the pattern: from 30 ABA + 24 ABC in second row, we get (30×3 + 24×2) + (30×2 + 24×2) = 138 + 108 = 246 ways.

Constraints

  • 1 ≤ n ≤ 5000
  • Grid is always n × 3 (exactly 3 columns)
  • Must use exactly 3 colors: Red, Yellow, Green
  • Answer must be computed modulo 109 + 7

Visualization

Tap to expand
Grid Coloring Evolution: ABA ↔ ABC TransitionsRow 1ABA: 6ABC: 6Row 2ABA: 30ABC: 24Row 3ABA: 138ABC: 108×3, ×2×3, ×2Transition RulesABA → ABA: ×3ABA → ABC: ×2ABC → ABA: ×2ABC → ABC: ×2Pattern: new_ABA = old_ABA×3 + old_ABC×2Pattern: new_ABC = old_ABA×2 + old_ABC×2
Understanding the Visualization
1
Initial State
Start with 6 ABA patterns and 6 ABC patterns for first row
2
Apply Transitions
Use rules: ABA→ABA(3), ABA→ABC(2), ABC→ABA(2), ABC→ABC(2)
3
Continue Pattern
Repeat transitions for each additional row until we reach n rows
Key Takeaway
🎯 Key Insight: By recognizing that valid rows follow only 2 patterns (ABA and ABC), we reduce the problem from exponential to linear time complexity using elegant transition rules!
Asked in
Google 45 Meta 38 Microsoft 32 Amazon 28
34.8K 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