Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour.

Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour.
def ways(n, k):
    same, diff = 0, k
    for _ in range(2, n + 1):
        same, diff = diff, (same + diff) * (k - 1)
    return same + diff
print(ways(4, 3))
What is printed?
  1. A. 81
  2. B. 48
  3. C. 54
  4. D. 66

Correct answer: D. 66

Track 'last two equal' (same) and 'last two different' (diff). n = 1: 0, 3; n = 2: 3, 6; n = 3: 6, 18; n = 4: 18, 48. Total 66. 81 = 3⁴ has no restriction; 48 counts only endings with different last two.

More Coding Interview Problems questions

Exams that ask this topic