The Paint Fence problem asks you to count the number of ways to paint n fence posts with k colors such that no more than 2 consecutive posts have the same color. This coding problem uses DP with two states: same-color (current matches previous) and different-color (current differs from previous). The dynamic programming interview pattern is cleanly demonstrated.
Meta, Snowflake, and Google ask this because it's a clean DP problem where the constraint "at most 2 consecutive same colors" leads to a simple two-state recurrence. It validates DP state design for sequence coloring problems.
Two-state DP. same[i] = ways to paint first i posts where post i has same color as post i-1. diff[i] = ways where post i has different color from post i-1. Recurrences: same[i] = diff[i-1] (can only extend different with same); diff[i] = (same[i-1] + diff[i-1]) * (k-1) (any previous state × k-1 choices). Answer = same[n] + diff[n].
n=3, k=2. Base: same[2]=2(k choices same), diff[2]=2(k choices, each has 1 different... wait: same[2]=k (all k colors for post 1, then same)? Let me recalculate:
Two-state DP problems where "current state depends on whether previous was same or different" are common in sequence coloring and tiling. Always define states to capture the relevant history. Here, knowing whether the last two posts were same or different is sufficient to enforce the "at most 2 consecutive same" constraint. Practice Paint Fence I, then extend to k-consecutive limit variants.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Ways to Express an Integer as Sum of Powers | Medium | Solve | |
| Count Ways To Build Good Strings | Medium | Solve | |
| Domino and Tromino Tiling | Medium | Solve | |
| Knight Probability in Chessboard | Medium | Solve | |
| Number of Dice Rolls With Target Sum | Medium | Solve |