Bitwise OR of Sums of All Subsequences

viaLeetCode

Problem: Given an array of n integers, consider all 2^n possible subsequences (including the empty subsequence). Compute the sum of each subsequence, then return the bitwise OR of all these sums.

Constraints: n can be moderately large, so enumerating all 2^n subsequences explicitly may be too slow for bigger inputs; an efficient bit-level approach is expected.

Example: arr = [1, 1] -> subsequences: {}, {1}, {1}, {1,1} with sums 0, 1, 1, 2 -> bitwise OR = 0 | 1 | 1 | 2 = 3.

Approach: Naive: recursively generate all subset sums (subset-sum recursion) and OR them together - O(2^n) time, fine only for small n. Optimized insight: the bitwise OR of all subset sums equals the bitwise OR obtained by, for each bit position, checking whether it's possible to form a subset sum that has that bit set - which can often be derived from the total sum and reasoning about which bits can be "reached" via subset combinations, avoiding full enumeration for large n.

Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account