Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (longest path in a DAG using topological order)
What is printed? (longest path in a DAG using topological order)
g = {'A': [('B', 3), ('C', 2)], 'B': [('D', 4)], 'C': [('D', 1), ('E', 6)], 'D': [('F', 2)], 'E': [('F', 1)], 'F': []}
order = ['A', 'B', 'C', 'D', 'E', 'F']
dist = {v: float('-inf') for v in g}; dist['A'] = 0
for u in order:
for v, w in g[u]:
dist[v] = max(dist[v], dist[u] + w)
print(dist['F'], dist['D'])- A. 9 3
- B. 8 7
- C. 11 7
- D. 9 7
Correct answer: D. 9 7
Process vertices in topological order and relax with max instead of min. D = max(A→B→D = 7, A→C→D = 3) = 7; F = max(D + 2 = 9, E + 1 = 8 + 1 = 9) = 9. Longest path is NP-hard in general graphs but O(V + E) in a DAG.
Practise more Trees, Graphs, Recursion and Dynamic Programming questionsTrees, Graphs, Recursion and Dynamic Programming: notes and key points
More Trees, Graphs, Recursion and Dynamic Programming questions
- What is printed? (unique paths count with memoised recursion vs closed form) python from functools import lrucache from math import comb…
- What is printed? (LIS length with O(n²) DP and the number of LIS) python a = [1, 3, 5, 4, 7] n = len(a); L = [1] n; C = [1] n for i in…
- What is printed? (coin change: number of combinations) python def ways(coins, amt): dp = [1] + [0] amt for c in coins: for a in range(c…
- What is printed? (rod cutting – maximise revenue) python price = [0, 1, 5, 8, 9, 10, 17, 17, 20] n = 8; r = [0] (n + 1) for j in range(1…
- What is printed? (subset sum with a boolean DP table) python a = [3, 34, 4, 12, 5, 2] def can(t): dp = [True] + [False] t for x in a: for…
- What is printed? (egg dropping: minimum trials in the worst case) python def trials(eggs, floors): # dp[m] = max floors checkable with m…