Subsets II solution explained

Subsets II asks for every distinct subset of a list that can contain repeated values. Sort the list so equal values sit together, then either backtrack and skip a value equal to the one just tried at the same depth, or build subsets level by level and let a repeated value extend only the subsets made in the previous round. Both produce each distinct subset once, in O(2^n × n) time in the worst case.

By Published 8 min read

The problem, in plain terms

You are given a list of integers, possibly with repeats. Return all subsets, including the empty one and the whole list. A subset is defined by which values it holds and how many copies of each, so two subsets that hold the same values in the same quantities are one answer, even if they were taken from different positions. Order inside a subset and order of the output are usually free.

list: 3 3 3 1

distinct subsets (8):
  []    [1]
  [3]   [1, 3]
  [3, 3]   [1, 3, 3]
  [3, 3, 3]   [1, 3, 3, 3]

choosing positions instead gives 2^4 = 16 subsets,
because each of [3] and [1, 3] can be made 3 ways, and so on.
A worked example, made up for this page

There is a quick way to check any answer: a value that appears c times can be taken zero, one, up to c times, so it contributes c + 1 choices. Here the 3 appears three times (4 choices) and the 1 once (2 choices), and 4 × 2 = 8. If your output has a different count, something is either missing or repeated.

Why interviewers follow Subsets with this one

The plain power set problem with distinct values has several clean solutions: recursion that includes or excludes each element, a loop that copies every existing subset and adds the new element, or counting from 0 to 2^n - 1 and reading the bits. Repeated values break all three in the same way, and the interviewer wants to see whether you fix the generator or reach for a set to hide the damage. Fixing the generator is the stronger answer, though mentioning the set version as a baseline is fine.

Brute force: enumerate positions, then dedupe

Sort the list, walk every bitmask from 0 to 2^n - 1, build the subset of positions whose bits are set, and put it into a set as a tuple. Sorting is what makes [1, 3] and [3, 1] the same tuple. This is correct and short, but it creates all 2^n position subsets even when only a handful of distinct ones exist. For a list of ten copies of the same number, it makes 1,024 subsets to keep 11.

Approach 1: backtracking where every node is an answer

Picture a recursion tree. The root is the empty subset. A node's children add one more element, always from a position after the last one used. Unlike combination problems with a target, every node in this tree is an answer, so the function records the current pick as soon as it is entered. To avoid repeats, sort first and, inside one loop, skip a value equal to the previous value when it is not the first one offered in this loop. The first 3 is offered at a given depth; the second and third 3s are not offered at that same depth, but they remain reachable one level down, which is how [3, 3] and [3, 3, 3] still appear.

def unique_subsets(nums):
    nums = sorted(nums)
    out, pick = [], []

    def go(start):
        out.append(pick[:])             # every node of the tree is an answer
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            pick.append(nums[i])
            go(i + 1)
            pick.pop()

    go(0)
    return out
Python: record at every node, skip equal values within one loop.

Approach 2: build level by level and track the last round

The iterative version for distinct values starts with [[]] and, for each element, appends a copy of every existing subset with that element added. With repeats, the trick is to notice which subsets would produce duplicates. When the current value equals the previous one, adding it to an old subset (one that existed before the previous value was processed) recreates something the previous round already made. Only the subsets created in the previous round, which already contain the earlier copy, can take this copy without repeating. So remember the index where the last round's additions began and start from there.

function uniqueSubsets(nums) {
  const sorted = nums.slice().sort((a, b) => a - b);
  const out = [[]];
  let lastRoundStart = 0;
  for (let i = 0; i < sorted.length; i++) {
    const from = i > 0 && sorted[i] === sorted[i - 1] ? lastRoundStart : 0;
    const size = out.length;
    for (let j = from; j < size; j++) out.push([...out[j], sorted[i]]);
    lastRoundStart = size;
  }
  return out;
}
JavaScript: a repeated value extends only the subsets added in the previous round.

Trace it on the sorted list 1, 3, 3, 3. After the 1: [], [1]. The first 3 extends both: [3], [1, 3]. The second 3 equals the previous value, so it extends only the two subsets from the last round: [3, 3], [1, 3, 3]. The third 3 extends only those two: [3, 3, 3], [1, 3, 3, 3]. That is the eight answers from the example, with no duplicates and no set. Setting lastRoundStart = size before the next element runs is the line people forget.

A third view: choose a count per distinct value

Count each distinct value, then for each one decide how many copies to include, from zero to its count. That decision tree has exactly the product of (count + 1) leaves, one per answer, so nothing is wasted. It is the same idea as the grouped version of Combination Sum II without the target, and it is the clearest way to prove the count formula above.

Complexity summary

n values, S distinct subsets (S is at most 2^n)
ApproachTimeExtra space
Bitmask over positions, set to dedupeO(2^n × n)O(S × n) for the set
Sorted backtracking with the skipO(n log n + S × n)O(n) recursion, plus the output
Level-by-level with lastRoundStartO(n log n + S × n)Only the output
Count per distinct valueO(n + S × n)O(d) for d distinct values, plus the output
n values, S distinct subsets (S is at most 2^n). Scroll sideways on a small screen.

The factor n comes from copying each subset into the output. In the worst case, all values distinct, S is 2^n and every approach is O(2^n × n). The fixed generators win when there are many repeats, because their cost tracks S rather than 2^n.

Edge cases to test

  • An empty list: the only answer is the empty subset, so the result is [[]], not [].
  • All values equal: n + 1 answers, from [] up to the full list.
  • All values distinct: 2^n answers, the plain power set.
  • Negative numbers and zero mixed in with repeats, to check that sorting still groups equal values.
  • The input left unchanged, if the interviewer cares (both versions above sort a copy or a local name).

Common mistakes

  • Recording a subset only at the leaves, which keeps only the full list and misses every smaller subset.
  • Using i > 0 in the skip instead of i > start, which deletes [3, 3] and [3, 3, 3].
  • In the iterative version, starting from lastRoundStart even when the value is new. A new value must extend every existing subset.
  • Updating lastRoundStart before reading out.length, so the round boundary points at the wrong place.
  • Writing out[j].push(value) instead of building a new array, which changes subsets already stored in the output.

How to explain it out loud

Fictional example

Leading with the count check
Candidate
Before I code, a sanity check. Three 3s and one 1 should give four choices times two choices, so eight subsets. That number will tell me if I'm producing duplicates.
Candidate
I'll sort so equal values are adjacent and build level by level. A new value extends every subset. A repeated value only extends the ones I added in the last round, because the older ones would just recreate what the previous copy made.
Candidate
So I keep one index for where the last round began. Time is the number of distinct subsets times their length, plus the sort.

Add a target sum and the same skip rule solves Combination Sum II. Track orderings instead of groups and it becomes Permutations II. The count-per-value view starts with a frequency count, the same first step as First Unique Character in a String.

Natively for power set practice

Subset problems are easy to get almost right, which is why a quick count check is worth practicing aloud. Natively, a desktop app for Mac and Windows, can read a practice problem from a screenshot and draft an approach with code that you can measure your own against. Afterward its transcript shows whether you stated the count before coding. See how AI fits into LeetCode-style practice.

Questions people ask

How do you solve Subsets II?

Sort the list so equal values are adjacent. Then backtrack, recording the current subset at every node and skipping a value equal to the previous one within the same loop, or build level by level and let a repeated value extend only the subsets added in the previous round.

How many subsets does a list with duplicates have?

Multiply (count + 1) over every distinct value. A value that appears c times can be included zero to c times. For 3, 3, 3, 1 that is 4 × 2 = 8 distinct subsets.

What is the time complexity of Subsets II?

O(n log n) for sorting plus O(S × n) to build S distinct subsets. In the worst case, with all values distinct, that is O(2^n × n).

Why do I get duplicate subsets?

Usually because the list was not sorted, so equal values are not neighbors, or because the skip compares against i > 0 instead of the loop start, or because a repeated value extends every subset instead of only the last round's.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP