Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP.
Problem: Maximum independent set (largest set of pairwise non-adjacent nodes) in a TREE with a two-state DP.
from collections import defaultdict
E = [(0,1),(0,2),(1,3),(1,4),(2,5),(5,6),(5,7),(7,8)]
g = defaultdict(list)
for u, v in E: g[u].append(v); g[v].append(u)
def go(u, p):
take, skip = 1, 0
for v in g[u]:
if v != p:
t, s = go(v, u); take += s; skip += max(t, s)
return take, skip
print(max(go(0, -1)))What is printed?- A. 4
- B. 6
- C. 9
- D. 5
Correct answer: D. 5
take = 1 + Σ skip(child), skip = Σ max(child). Leaves 3, 4 and 6, 8 are always worth taking; then 2 can be added (its child 5 is excluded because of 6) — e.g. {3, 4, 2, 6, 8} = 5. Greedy 'take all leaves' happens to be optimal here but not in general.
More Coding Interview Problems questions
- Edge case: greedy coin change versus DP when the coin system is not canonical. python def greedy(coins, x): cnt = 0 for c in sorted(coins…
- Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters). python def ways(n): dp = [1] + [0] n for i in…
- Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity. python def frac(items…
- Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort. python def lomuto(a): p = a[-1]; i = -1 for j in…
- Problem: Count the swaps made by bubble sort and by selection sort on the same array. python def bubble(a): a = a[:]; s = 0 for i in…
- Problem: Bottom-up heapify (max-heap) of an array; print the resulting array. python def heapify(a): n = len(a) def down(i): while True…