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?
  1. A. [[], [], [], []]
  2. B. [[], [2], [1], [1, 2]]
  3. C. [[1, 2], [1, 2], [1, 2], [1, 2]]
  4. 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

Exams that ask this topic