You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo109 + 7.
Example 1:
Input: m = 1, n = 1
Output: 3
Explanation: The three possible colorings are shown in the image above.
Example 2:
Input: m = 1, n = 2
Output: 6
Explanation: The six possible colorings are shown in the image above.
Problem summary: You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted. Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 109 + 7.
Baseline thinking
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Dynamic Programming
Example 1
1
1
Example 2
1
2
Example 3
5
5
Related Problems
Number of Ways to Paint N × 3 Grid (number-of-ways-to-paint-n-3-grid)
Step 02
Core Insight
What unlocks the optimal approach
Represent each colored column by a bitmask based on each cell color.
Use bitmasks DP with state (currentCell, prevColumn).
Interview move: turn each hint into an invariant you can check after every iteration/recursion step.
Step 03
Algorithm Walkthrough
Iteration Checklist
Define state (indices, window, stack, map, DP cell, or recursion frame).
Apply one transition step and update the invariant.
Record answer candidate when condition is met.
Continue until all input is consumed.
Use the first example testcase as your mental trace to verify each transition.
Step 04
Edge Cases
Minimum Input
Single element / shortest valid input
Validate boundary behavior before entering the main loop or recursion.
Duplicates & Repeats
Repeated values / repeated states
Decide whether duplicates should be merged, skipped, or counted explicitly.
Extreme Constraints
Largest constraint values
Re-check complexity target against constraints to avoid time-limit issues.
Invalid / Corner Shape
Empty collections, zeros, or disconnected structures
Handle special-case structure before the core algorithm path.
Step 05
Full Annotated Code
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1931: Painting a Grid With Three Different Colors
class Solution {
private int m;
public int colorTheGrid(int m, int n) {
this.m = m;
final int mod = (int) 1e9 + 7;
int mx = (int) Math.pow(3, m);
Set<Integer> valid = new HashSet<>();
int[] f = new int[mx];
for (int i = 0; i < mx; ++i) {
if (f1(i)) {
valid.add(i);
f[i] = 1;
}
}
Map<Integer, List<Integer>> d = new HashMap<>();
for (int i : valid) {
for (int j : valid) {
if (f2(i, j)) {
d.computeIfAbsent(i, k -> new ArrayList<>()).add(j);
}
}
}
for (int k = 1; k < n; ++k) {
int[] g = new int[mx];
for (int i : valid) {
for (int j : d.getOrDefault(i, List.of())) {
g[i] = (g[i] + f[j]) % mod;
}
}
f = g;
}
int ans = 0;
for (int x : f) {
ans = (ans + x) % mod;
}
return ans;
}
private boolean f1(int x) {
int last = -1;
for (int i = 0; i < m; ++i) {
if (x % 3 == last) {
return false;
}
last = x % 3;
x /= 3;
}
return true;
}
private boolean f2(int x, int y) {
for (int i = 0; i < m; ++i) {
if (x % 3 == y % 3) {
return false;
}
x /= 3;
y /= 3;
}
return true;
}
}
// Accepted solution for LeetCode #1931: Painting a Grid With Three Different Colors
func colorTheGrid(m int, n int) (ans int) {
f1 := func(x int) bool {
last := -1
for i := 0; i < m; i++ {
if x%3 == last {
return false
}
last = x % 3
x /= 3
}
return true
}
f2 := func(x, y int) bool {
for i := 0; i < m; i++ {
if x%3 == y%3 {
return false
}
x /= 3
y /= 3
}
return true
}
mx := int(math.Pow(3, float64(m)))
valid := map[int]bool{}
f := make([]int, mx)
for i := 0; i < mx; i++ {
if f1(i) {
valid[i] = true
f[i] = 1
}
}
d := map[int][]int{}
for i := range valid {
for j := range valid {
if f2(i, j) {
d[i] = append(d[i], j)
}
}
}
const mod int = 1e9 + 7
for k := 1; k < n; k++ {
g := make([]int, mx)
for i := range valid {
for _, j := range d[i] {
g[i] = (g[i] + f[j]) % mod
}
}
f = g
}
for _, x := range f {
ans = (ans + x) % mod
}
return
}
# Accepted solution for LeetCode #1931: Painting a Grid With Three Different Colors
class Solution:
def colorTheGrid(self, m: int, n: int) -> int:
def f1(x: int) -> bool:
last = -1
for _ in range(m):
if x % 3 == last:
return False
last = x % 3
x //= 3
return True
def f2(x: int, y: int) -> bool:
for _ in range(m):
if x % 3 == y % 3:
return False
x, y = x // 3, y // 3
return True
mod = 10**9 + 7
mx = 3**m
valid = {i for i in range(mx) if f1(i)}
d = defaultdict(list)
for x in valid:
for y in valid:
if f2(x, y):
d[x].append(y)
f = [int(i in valid) for i in range(mx)]
for _ in range(n - 1):
g = [0] * mx
for i in valid:
for j in d[i]:
g[i] = (g[i] + f[j]) % mod
f = g
return sum(f) % mod
// Accepted solution for LeetCode #1931: Painting a Grid With Three Different Colors
/**
* [1931] Painting a Grid With Three Different Colors
*
* You are given two integers m and n. Consider an m x n grid where each cell is initially white. You can paint each cell red, green, or blue. All cells must be painted.
* Return the number of ways to color the grid with no two adjacent cells having the same color. Since the answer can be very large, return it modulo 10^9 + 7.
*
* Example 1:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/22/colorthegrid.png" style="width: 200px; height: 50px;" />
* Input: m = 1, n = 1
* Output: 3
* Explanation: The three possible colorings are shown in the image above.
*
* Example 2:
* <img alt="" src="https://assets.leetcode.com/uploads/2021/06/22/copy-of-colorthegrid.png" style="width: 321px; height: 121px;" />
* Input: m = 1, n = 2
* Output: 6
* Explanation: The six possible colorings are shown in the image above.
*
* Example 3:
*
* Input: m = 5, n = 5
* Output: 580986
*
*
* Constraints:
*
* 1 <= m <= 5
* 1 <= n <= 1000
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/painting-a-grid-with-three-different-colors/
// discuss: https://leetcode.com/problems/painting-a-grid-with-three-different-colors/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn color_the_grid(m: i32, n: i32) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_1931_example_1() {
let m = 1;
let n = 1;
let result = 3;
assert_eq!(Solution::color_the_grid(m, n), result);
}
#[test]
#[ignore]
fn test_1931_example_2() {
let m = 1;
let n = 2;
let result = 6;
assert_eq!(Solution::color_the_grid(m, n), result);
}
#[test]
#[ignore]
fn test_1931_example_3() {
let m = 5;
let n = 5;
let result = 580986;
assert_eq!(Solution::color_the_grid(m, n), result);
}
}
// Accepted solution for LeetCode #1931: Painting a Grid With Three Different Colors
function colorTheGrid(m: number, n: number): number {
const f1 = (x: number): boolean => {
let last = -1;
for (let i = 0; i < m; ++i) {
if (x % 3 === last) {
return false;
}
last = x % 3;
x = Math.floor(x / 3);
}
return true;
};
const f2 = (x: number, y: number): boolean => {
for (let i = 0; i < m; ++i) {
if (x % 3 === y % 3) {
return false;
}
x = Math.floor(x / 3);
y = Math.floor(y / 3);
}
return true;
};
const mx = 3 ** m;
const valid = new Set<number>();
const f: number[] = Array(mx).fill(0);
for (let i = 0; i < mx; ++i) {
if (f1(i)) {
valid.add(i);
f[i] = 1;
}
}
const d: Map<number, number[]> = new Map();
for (const i of valid) {
for (const j of valid) {
if (f2(i, j)) {
d.set(i, (d.get(i) || []).concat(j));
}
}
}
const mod = 10 ** 9 + 7;
for (let k = 1; k < n; ++k) {
const g: number[] = Array(mx).fill(0);
for (const i of valid) {
for (const j of d.get(i) || []) {
g[i] = (g[i] + f[j]) % mod;
}
}
f.splice(0, f.length, ...g);
}
let ans = 0;
for (const x of f) {
ans = (ans + x) % mod;
}
return ans;
}
Step 06
Interactive Study Demo
Use this to step through a reusable interview workflow for this problem.
Press Step or Run All to begin.
Step 07
Complexity Analysis
Time
O((m + n)
Space
O(3^m)
Approach Breakdown
RECURSIVE
O(2ⁿ) time
O(n) space
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
DYNAMIC PROGRAMMING
O(n × m) time
O(n × m) space
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Shortcut: Count your DP state dimensions → that’s your time. Can you drop one? That’s your space optimization.
Coach Notes
Common Mistakes
Review these before coding to avoid predictable interview regressions.
State misses one required dimension
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.