← Questions

Count colorings of a row of houses with fixed end colors

0
GoogleCoding

A coding interview question asked at Google. It tests dynamic programming, combinatorics and math.

A contractor is repainting a row of n houses, numbered 0 to n - 1. There are k paint colors, numbered 0 to k - 1.

The new paint job must follow two rules:

  • Two neighboring houses (i and i + 1) never have the same color.
  • House 0 must be painted first and house n - 1 must be painted last. Both colors are given.

Implement:

def count_ways(n: int, k: int, first: int, last: int) -> int:
    ...

Return the number of valid colorings modulo 10^9 + 7. If no coloring is valid (for example, a color is out of range), return 0.

Constraints

  • 1 <= n <= 10^18
  • 1 <= k <= 10^9
  • first and last are integers. They may be outside 0..k-1.
  • When n == 1, house 0 is both the first and the last house.

Example 1

n = 3, k = 3, first = 0, last = 0  ->  2

The valid rows are 0 1 0 and 0 2 0.

Example 2

n = 4, k = 3, first = 0, last = 2  ->  3

The valid rows are 0 1 0 2, 0 2 0 2, and 0 2 1 2.

Start with an approach that works for n up to 10^5, then make it fast enough for n = 10^18.

Clarifying questions

  • With k = 1, is the only possible case n = 1 with first == last == 0?
  • When n == 1 and first != last, is the answer 0?
  • Should colors outside 0..k-1 return 0 rather than raise an error?
  • Is the modulus applied only to the final count, and is 10^9 + 7 fixed?

What a strong answer covers

  • A dynamic program first: after house i, track same (colorings so far whose last house has color last) and other (those ending in one specific other color; by symmetry every other color has the same count). Each step is O(1), so it is O(n) for n up to 10^5.
  • Makes it fast by writing that step as a 2 x 2 matrix and raising it to the power n - 1 by repeated squaring, O(log n). Alternatively, uses the closed form for proper colorings of a path with fixed ends, which involves (k - 1)^(n - 1), a (-1)^(n - 1) term and a division by k done with a modular inverse.
  • Uses pow(base, exp, mod) and a modular inverse, and checks that k is not a multiple of the modulus (it can't be, since k <= 10^9).
  • Edge cases: n = 1, n = 2 with first == last (0 ways), k = 1, k = 2 (at most one valid row), and colors out of range.
  • Tests: both examples, the edge cases, and a brute-force count over all rows for small n and k.

Follow-ups

  • The houses form a ring instead of a row.
  • Some houses already have a fixed color in the middle.
  • Each color has a price: find the cheapest valid coloring.
  • No two houses at distance 2 may share a color either.

Where it's asked

What it tests

dynamic programming · combinatorics · math · matrix exponentiation

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding