Math Fundamentals18 sections · 814 units
Open in Course

Subsets - Implementation

The code

Here's the complete bitmask solution:


function subsets(nums)
    n := length of nums
    total := 2^n
    result := []
    for mask from 0 to total - 1
        subset := []
        for i from 0 to n - 1
            if (mask & (1 << i))  0 then
                append nums[i] to subset
        append subset to result
    return result

Outer loop generates all 2n2^n masks. Inner loop builds each subset by checking which bits are set. Time: O(n×2n)O(n \times 2^n) (for each of 2n2^n masks, you check nn bits). Space: O(n×2n)O(n \times 2^n) for the output.