Question presented to candidate: "Given a list of distinct integers, return every possible subset โ the power set. Code it in Python, then tell me what changes if the list can contain duplicates."
What a strong answer should cover:
- Every element is either in or out, so there are 2^n subsets including the empty one; that bounds both time and output size.
- A backtracking solution (loop from a start index, choose / recurse with i + 1 / un-choose) and why the start index prevents reordered repeats.
- At least one alternative: the iterative doubling (cascade) or the bitmask from 0 to 2^n - 1.
- Complexity O(n ยท 2^n) time and output, O(n) extra space for the recursion, and why it cannot be beaten when every subset must be listed.
- Duplicates (Subsets II): sort, then skip a value equal to the previous one at the same level (
i > start). - Python details: record
path[:](a copy) notpath;itertools.combinationsgives the same sets ordered by size;1 << nis exact for any n because Python integers do not overflow.
Clarifying questions expected:
- Can the input contain duplicates, and if so should equal subsets appear once?
- Does the order of the subsets (or inside each subset) matter?
- How large can n get? (2^n grows very fast.)
Code / implementation expected: Yes โ a backtracking function in Python returning list[list[int]], plus the sort-and-skip change for duplicates.