Number of Ways to Paint N × 3 Grid

hard dynamic programming combinatorics modular arithmetic

Problem

Paint every cell of an n × 3 grid with one of three colors (Red, Yellow, Green) so that no two cells sharing a side have the same color. Return the number of valid colorings modulo 109 + 7.

Inputn = 1
Output12
A single row of 3 cells has 3 · 2 · 2 = 12 valid colorings.
Inputn = 2
Output54
Each of the 12 first rows extends into either 5 or 4 second rows, giving 54 total.

def num_of_ways(n):
    MOD = 10**9 + 7
    aba, abc = 6, 6          # rows of form ABA and ABC
    for _ in range(n - 1):
        aba, abc = (3 * aba + 2 * abc) % MOD, \
                   (2 * aba + 2 * abc) % MOD
    return (aba + abc) % MOD
function numOfWays(n) {
  const MOD = 1000000007n;
  let aba = 6n, abc = 6n;          // rows of form ABA and ABC
  for (let i = 1; i < n; i++) {
    const a = (3n * aba + 2n * abc) % MOD;
    const c = (2n * aba + 2n * abc) % MOD;
    aba = a; abc = c;
  }
  return Number((aba + abc) % MOD);
}
int numOfWays(int n) {
    long MOD = 1_000_000_007L;
    long aba = 6, abc = 6;          // rows of form ABA and ABC
    for (int i = 1; i < n; i++) {
        long a = (3 * aba + 2 * abc) % MOD;
        long c = (2 * aba + 2 * abc) % MOD;
        aba = a; abc = c;
    }
    return (int) ((aba + abc) % MOD);
}
int numOfWays(int n) {
    const long long MOD = 1000000007LL;
    long long aba = 6, abc = 6;     // rows of form ABA and ABC
    for (int i = 1; i < n; i++) {
        long long a = (3 * aba + 2 * abc) % MOD;
        long long c = (2 * aba + 2 * abc) % MOD;
        aba = a; abc = c;
    }
    return (int) ((aba + abc) % MOD);
}
Time: O(n) Space: O(1)