Problem 1411

Abstract / Summary

Count the ways to color each row of a tall narrow grid so that no two side cells share a color, using at most three colors.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1411.py

class Solution:
    def numOfWays(self, n: int) -> int:
        modulo = 1_000_000_007

        match = {}
        for a in range(3):
            for b in range(3):
                for c in range(3):
                    if a != b and b != c:
                        match[str(a) + str(b) + str(c)] = []
                        # 010, 012, 020, 021, 101, 102, 120, 121, 201, 202, 210, 212

        # figure out for each valid row what rows are "compatible" (can be painted next to it)
        for x in match:
            for y in match:
                if x[0] != y[0] and x[1] != y[1] and x[2] != y[2]:
                    match[x].append(y)

        have = { row : 1 for row in match } # 12 ones

        for i in range(n - 1):
            next = { row : 0 for row in match }
            for pattern in have:
                for follow in match[pattern]:
                    next[follow] += have[pattern]
            have = next

        return sum(have.values()) % modulo
28 lines | 1002 bytes | submitted March 12, 2024 | GitHub   14% comment ratio | tab size 4 | moderate complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 81% (100k+ submissions).

Typical patterns to solve this problem:
  • Dynamic Programming
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the combinatorial problem of counting the number of ways to paint an n × 3 grid using three colors (0, 1, 2) such that no two adjacent cells-horizontally or vertically-share the same color. The algorithm enumerates all valid row patterns, pre-computes compatibility between rows, and then uses dynamic programming to propagate counts across the n rows. A large prime modulus (1_000_000_007) is applied to keep the result within integer limits.

Key Steps

The first logical block builds the set of all row patterns that satisfy the horizontal adjacency rule. The nested loops iterate over the three possible colors for each of the three columns, and a pattern is stored only when adjacent columns differ.

match = {}
for a in range(3):
    for b in range(3):
        for c in range(3):
            if a != b and b != c:
                match[str(a) + str(b) + str(c)] = []

At this point match contains twelve keys, each representing a three-character string such as "010" or "212".

The second block determines vertical compatibility. For every pair of stored patterns, the algorithm checks that the colors in each column differ, and if so, records the second pattern as a possible successor of the first.

for x in match:
    for y in match:
        if x[0] != y[0] and x[1] != y[1] and x[2] != y[2]:
            match[x].append(y)

The compatibility lists are stored directly in the match dictionary, turning it into an adjacency map.

The dynamic programming stage initializes a dictionary have that maps each valid row pattern to the count of ways it can appear as the first row. Since any of the twelve patterns can start the grid, each entry is set to 1.

have = { row : 1 for row in match }

The core loop runs n-1 times, each iteration constructing a new dictionary next that aggregates counts for the next row based on the current have values and the pre-computed compatibility lists.

for i in range(n - 1):
    next = { row : 0 for row in match }
    for pattern in have:
        for follow in match[pattern]:
            next[follow] += have[pattern]
    have = next

After processing all rows, the final answer is the sum of the counts for the last row, reduced modulo the large prime.

return sum(have.values()) % modulo

Edge Cases Handled

When n equals 1, the outer loop (for i in range(n - 1)) executes zero times, leaving have unchanged with each of the twelve patterns counted exactly once. The final summation therefore returns 12, which is the correct number of ways to paint a single row under the horizontal constraint.

If n is larger than 1, the algorithm correctly propagates counts through all rows because the compatibility map guarantees that only vertically valid transitions are considered. The use of string keys for patterns ensures that the adjacency check (x[0] != y[0] etc.) works uniformly regardless of the numeric values of the colors.

The modulo operation applied at the very end guarantees that even for very large n the result fits within standard integer ranges, preventing overflow while preserving the exact count modulo the specified prime.

Performance Optimizations

The code pre-computes the compatibility relationships between rows once, before the dynamic programming loop. By storing the list of compatible successors for each pattern, the inner update step avoids recomputing column-wise comparisons during each iteration, reducing the per-iteration work to simple dictionary lookups and integer additions.

The use of dictionaries keyed by the pattern strings provides constant-time access to both the current count (have[pattern]) and the list of successors (match[pattern]). This choice eliminates the need for nested loops over all possible color combinations during the DP phase.

The algorithm also reuses the same dictionary structures (have and next) across iterations, creating a fresh next dictionary each time but discarding the previous one only after its values have been fully transferred. This approach avoids the accumulation of stale data and keeps memory usage bounded by the number of valid patterns (twelve) rather than by n.

Finally, the final modulo operation is performed only once after the entire DP process, rather than after each addition. This reduces the number of expensive modulo operations, which can be beneficial when n is large.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have a row of three blocks that you want to color using three different colors. You can color them such that no two neighbor blocks have the same color. There are twelve different ways to color one single row following these rules.

The computer starts by making a list of all twelve of these valid patterns. Then, it looks at how the rows can be stacked on top of each other. A new row can only be placed under the current row if every block has a different color than the one directly above it.

The code keeps track of how many ways each pattern can be built as it adds more rows one by one. It starts by saying there is one way to have each of the twelve patterns for the very first row. Then, for every row added after that, it looks at the previous patterns and adds up all the choices that are allowed. It keeps doing this until the whole stack reaches the height requested. Because the number of ways can get very, very large, it uses a special trick with a big number to keep the count manageable for the computer. After checking every possible row stack, it adds up all the different ways the final row could look.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 6.81 | σ = 1.06

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Java
leetcode.ca C++ Python Go Java Rust TS
Progiez C++ Python Java
github everthis JS
fsq C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
wisdompeak C++
withaarzoo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, Go, Java, Python, Rust, TypeScript
Progiez C++, Java, Python
everthis JavaScript
fsq C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
wisdompeak C++
withaarzoo C++
24 links | 13 authors | 7 languages

Videos

6 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

4 solutions   March 12, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality