LeetCode Challenge Day 110 β 1411. Number of Ways to Paint N Γ 3 Grid
Nitin Ahirwal / January 3, 2026
Hey folks π
This is Day 110 of my LeetCode streak π
Today's problem is 1411. Number of Ways to Paint N Γ 3 Grid β a classic dynamic programming problem where observation simplifies a seemingly complex grid-coloring task.
π Problem Statement
You are given:
- A grid of size
n Γ 3 - Three colors: Red, Yellow, Green
- No two adjacent cells (horizontal or vertical) can have the same color
Goal:
Return the total number of valid ways to paint the grid.
Since the number can be large, return it modulo 10βΉ + 7.
π‘ Intuition
Instead of coloring the entire grid at once, focus on one row at a time.
For a single row of 3 cells, valid colorings fall into only two patterns:
-
ABA pattern
- First and third cells have the same color
- Middle cell is different
- Example:
R G R
-
ABC pattern
- All three cells have different colors
- Example:
R Y G
Each pattern has 6 possible colorings, so for n = 1, total ways = 12.
The key realization:
The coloring of the current row depends only on the pattern of the previous row, not the exact colors.
This allows us to track just two states instead of all combinations.
π Approach
- Use dynamic programming with state compression
- Maintain two variables:
sameβ number of ways where the row follows the ABA patterndiffβ number of ways where the row follows the ABC pattern
- Initialize for the first row:
same = 6diff = 6
- For each new row:
- New
samecan be formed from:- previous
samerows in3ways - previous
diffrows in2ways
- previous
- New
diffcan be formed from:- previous
samerows in2ways - previous
diffrows in2ways
- previous
- New
- Apply modulo at every step
Finally, return same + diff.
β±οΈ Complexity Analysis
-
Time Complexity:
O(n)β one pass through the rows -
Space Complexity:
O(1)β constant space using only two variables
π§βπ» Code (JavaScript)
/**
* @param {number} n
* @return {number}
*/
var numOfWays = function(n) {
const MOD = 1e9 + 7;
// Base case for first row
let same = 6; // ABA patterns
let diff = 6; // ABC patterns
for (let i = 2; i <= n; i++) {
const newSame = (same * 3 + diff * 2) % MOD;
const newDiff = (same * 2 + diff * 2) % MOD;
same = newSame;
diff = newDiff;
}
return (same + diff) % MOD;
};
π― Reflection
This problem is a perfect example of how:
-
Pattern recognition simplifies complex grids
-
State compression turns exponential problems into linear ones
-
Clean thinking beats brute force every time
That wraps up Day 110 of my LeetCode challenge π₯
Consistency > intensity β see you on Day 111 π
Happy Coding π¨βπ»