#78

Subsets

Medium
ArrayBacktrackingBit ManipulationBacktrackingBit Manipulation
LeetCode ↗

Approaches

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

Intuition

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

The optimal solution uses bit manipulation to represent subsets as binary numbers. Each bit in a binary number represents whether to include an element from the array or not.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize an empty list to store all subsets.
  2. 2Step 2: Iterate from 0 to 2^n (where n is the length of nums).
  3. 3Step 3: For each number, convert it to binary and use the bits to decide which elements to include in the current subset.
solution.py10 lines
1def subsets(nums):
2    n = len(nums)
3    result = []
4    for i in range(1 << n):
5        subset = []
6        for j in range(n):
7            if i & (1 << j):
8                subset.append(nums[j])
9        result.append(subset)
10    return result

Complexity note: The time complexity is O(n * 2^n) because we generate 2^n subsets and each subset can take up to O(n) time to construct. Space complexity is O(n) for the subset storage.

  • 1Each element can either be included or excluded from a subset.
  • 2The number of subsets grows exponentially with the number of elements.

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