DSA interview question
A recipe app lets users choose any combination of the ingredients they have, and some ingredients appear more than once (two eggs, three tomatoes). The app wants every distinct selection: taking "one of the two eggs" is the same selection no matter which egg. With duplicates, the plain power set lists the same multiset several times. The fix mirrors Combination Sum II: sort, build subsets by choosing the next element from start onward, and at each level try each distinct value only once. Every node of this recursion tree is a distinct subset.
Example: [1, 2, 2] → [] [1] [1,2] [1,2,2] [2] [2,2].
vector<vector<int>> subsetsWithDup(vector<int> nums); // lexicographic order
| Input | Output | Explanation |
|---|---|---|
[1, 2, 2] | [] [1] [1,2] [1,2,2] [2] [2,2] | 6 distinct subsets, not 8 |
[0] | [] [0] | |
[4, 4, 4, 1, 4] | [] [1] [1,4] [1,4,4] [1,4,4,4] [1,4,4,4,4] [4] [4,4] [4,4,4] [4,4,4,4] | 2 · 5 = 10 |
[3, 1] | [] [1] [1,3] [3] | No duplicates, so the plain power set |
[] | [] |
(Confirm: subsets are compared as multisets; each subset is output once; any order is acceptable, and sorted order is shown here.)
[1,2] the same as [2,1]? (Yes, multisets.)On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.
Book a free mock interviewAll 474 dsa interview questions
DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in