Data Structures & AlgorithmsModerateTCS NQT Digital · Product Company SDE
Problem: Find the bug: a backtracking routine collects all subsets of [1, 2].
Problem: Find the bug: a backtracking routine collects all subsets of [1, 2].
def subsets(a):
res, path = [], []
def bt(i):
if i == len(a): res.append(path); return
bt(i + 1)
path.append(a[i]); bt(i + 1); path.pop()
bt(0)
return res
print(subsets([1, 2]))What is printed?- A. [[], [], [], []]
- B. [[], [2], [1], [1, 2]]
- C. [[1, 2], [1, 2], [1, 2], [1, 2]]
- D. [[], [1], [2], [1, 2]]
Correct answer: A. [[], [], [], []]
res.append(path) stores a reference to the single shared list, not a snapshot. Every pop() eventually empties it, so all four entries are the same empty list at the end. Fix: res.append(path[:]) (or list(path)), which would print [[], [2], [1], [1, 2]].
More Coding Interview Problems questions
- Problem: Find the bug: a range-sum helper over a prefix array (pre[0] = 0, pre[i] = sum of the first i values) should return a[l] + … +…
- Problem: Find the bug: a list of multiplier functions is built in a loop with lambdas. python fs = [lambda x: x i for i in range(1, 4)] gs…
- Problem: Find the bug: even values are removed from a list while iterating over that same list. python nums = [2, 4, 4, 6, 5, 8] for x in…
- Problem: n ≤ 2·10⁵ values; count pairs i < j with (a[i] + a[j]) divisible by k. The O(n²) check times out; bucket by remainder and pair…
- Problem: A divide-and-conquer routine makes 3 recursive calls on halves and does linear extra work: T(n) = 3T(n/2) + n. The code evaluates…
- Problem: A sliding-window routine has a while loop nested inside a for loop. For a 12 000-character string, how many inner (left-pointer)…