DSA AnimatorREVISION VIDEOS
← Back to problems
New

Subsets II — LeetCode 90 video explanation

This time the array may contain duplicates. Return all subsets, without repeating any subset.

Loading videos…

DSA Animator › DSA Revision › Backtracking › Subsets II

Key moments in the Subsets II video

0:03Problem0:09Example0:17Brute force0:24Key idea0:37Dry run0:56Code1:08Takeaway

What you will learn

Remember: sort, then skip equal values at the same level. i greater than start is what allows 2, 2 deeper down. The video solves Subsets II (LeetCode 90, Medium) with the Backtracking + Skip Duplicates pattern from the Backtracking topic, and you can replay every step in the interactive Subsets II animation.

Subsets II video transcript

Problem

This time the array may contain duplicates. Return all subsets, without repeating any subset.

Example

For 1, 2, 2, there are 6 unique subsets. They are the empty set, 1, then 1, 2, then 1, 2, 2, then 2, and 2, 2.

Brute force

Generating all subsets and removing duplicates with a set wastes work. It is better never to build a duplicate at all.

Key idea

Sort the array, so equal numbers sit next to each other. Inside one loop level, skip a number if it equals the one just before it. Equal numbers can still be picked one after another deeper in the tree, like 2, 2.

Dry run

Record the empty set, then go to 1, then 1, 2, then 1, 2, 2. Back at 1, the second 2 equals the first one at the same level, so skip it. Back at the empty set, take 2, and then 2, 2. The second 2 at the top level is a duplicate start, so skip it too. That leaves exactly 6 subsets.

Code

In code, sort the numbers first. In the loop, continue if i is greater than start and the number equals the previous one. Otherwise choose, recurse and un-choose as before, so it's O of n times 2 to the n.

Takeaway

Remember: sort, then skip equal values at the same level. i greater than start is what allows 2, 2 deeper down.

More Backtracking revision videos

← All 185 DSA revision videos