Skip to the solution
MediumDSA11 min read

How do you generate all subsets of an array?

962 views

The problem

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) not path; itertools.combinations gives the same sets ordered by size; 1 << n is 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.

  • dsa
  • backtracking
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read ยท 12 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonPower set four ways: loop backtracking, take/skip, cascade, bitmask
PythonSubsets II: sort + skip duplicates, and output size for n up to 16

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 52 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you remove the nth node from the end of a linked list?

Continue