Dynamic Programming21 sections · 916 units
Open in Course

Subset Sum - Implementation

The code

Here's the full solution:

function subsetSumExists(arr, target)
    n := length of arr
    for mask := 0 to (1 << n) - 1
        sum := 0
        for i := 0 to n - 1
            if (mask >> i) & 1 = 1 then
                sum := sum + arr[i]
        if sum = target then
            return true
    return false

Time: O(2nn)O(2^n \cdot n). For each of 2n2^n masks, you check nn bits. Space: O(1)O(1) extra. This is your first complete bitmask solution. The pattern is simple: iterate masks, extract bits, compute answer.