Dynamic Programming21 sections · 916 units
Open in Course

Bit Problem - Implementation

Three SOS passes

Build a frequency array f[mask]f[\text{mask}] counting occurrences of each value. Then run two SOS passes:

function solveBitProblem(nums, maxVal)
    n := bits needed for maxVal
    f := frequency array of size 2^n
    sub := copy of f
    for i := 0 to n - 1
        for mask := 0 to 2^n - 1
            if (mask >> i) & 1 then
                sub[mask] += sub[mask ^ (1 << i)]
    sup := copy of f
    for i := 0 to n - 1
        for mask := 0 to 2^n - 1
            if not ((mask >> i) & 1) then
                sup[mask] += sup[mask | (1 << i)]
    ALL := 2^n - 1
    for x in nums
        print(sub[x], sup[x], len(nums) - sub[ALL ^ x])

Time: O(n2n)O(n \cdot 2^n) Each SOS pass, where n=log(max)n = \log(\max). Space: O(2n)O(2^n).

Time: O(n2n)O(n \cdot 2^n). Space: O(2n)O(2^n).