Build a frequency array counting occurrences of each value. Then run two SOS passes:
plaintext 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: Each SOS pass, where . Space: .
Time: . Space: .