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?- A. 81
- B. 48
- C. 54
- 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
- Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the…
- Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again. python def…
- Problem: Wildcard matching where '?' matches one character and '' matches any sequence (including empty); the whole string must match…
- Problem: Count the ways to partition a string into substrings that are all palindromes. python def parts(s): n = len(s); dp = [1] + [0] n…
- Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no…
- Problem: Check whether a number is a power of four with bit tricks. python def p4(n): return n > 0 and n & (n - 1) == 0 and n & 0x55555555…