Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (subset sum with a boolean DP table)
What is printed? (subset sum with a boolean DP table)
a = [3, 34, 4, 12, 5, 2]
def can(t):
dp = [True] + [False] * t
for x in a:
for s in range(t, x - 1, -1): dp[s] = dp[s] or dp[s - x]
return dp[t]
print(can(9), can(30), can(56))- A. True True True
- B. True False False
- C. True False True
- D. False False True
Correct answer: C. True False True
9 = 4 + 5. 30 cannot be formed: 34 is too big and the other values sum to only 26. 56 = 34 + 12 + 5 + 3 + 2. Iterating s downwards uses each number at most once (0/1 choice). O(n·t) time, O(t) space.
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? (egg dropping: minimum trials in the worst case) python def trials(eggs, floors): # dp[m] = max floors checkable with m…
- What is printed? (0/1 knapsack with item reconstruction) python w = [1, 3, 4, 5]; v = [1, 4, 5, 7]; W = 7; n = 4 dp = [[0] (W + 1) for in…
- What is printed? (number of BSTs vs number of binary heaps on keys 1..4) python from math import comb from functools import lrucache…
- What is printed? (diameter of an unweighted tree with two BFS passes) python from collections import deque edges = [(1, 2), (1, 3), (2…
- What is printed? (articulation points by brute force removal) python edges = [(0, 1), (1, 2), (2, 0), (1, 3), (3, 4), (4, 5), (5, 3), (5…
- What is printed? (strongly connected components count, Kosaraju) python g = {0: [1], 1: [2], 2: [0, 3], 3: [4], 4: [5], 5: [3], 6: [5, 7]…