#90

Subsets II

Medium
ArrayBacktrackingBit ManipulationBacktrackingSorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n * 2^n)
O(n * 2^n)
Space
O(2^n)
O(n)
💡

Intuition

Time O(n * 2^n)Space O(n)

The optimal solution uses backtracking to build subsets while ensuring that duplicates are avoided by skipping over duplicate elements. This is more efficient than generating all subsets and filtering them afterward.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the input array to group duplicates together.
  2. 2Step 2: Use a backtracking function to build subsets, adding elements only if they are not duplicates of the previous element at the same level.
  3. 3Step 3: Add each valid subset to the result list.
solution.py13 lines
1def subsetsWithDup(nums):
2    nums.sort()
3    result = []
4    def backtrack(start, path):
5        result.append(path[:])
6        for i in range(start, len(nums)):
7            if i > start and nums[i] == nums[i - 1]:
8                continue
9            path.append(nums[i])
10            backtrack(i + 1, path)
11            path.pop()
12    backtrack(0, [])
13    return result

Complexity note: The time complexity remains O(n * 2^n) due to the nature of generating subsets, but the space complexity is O(n) for the recursion stack and the result storage.

  • 1Sorting the array helps in efficiently skipping duplicates.
  • 2Backtracking allows us to explore all combinations without generating all subsets upfront.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.