Problem Description
Given an integer array nums, return the bitwise OR of the sum of all possible subsequences in the array. A subsequence is a sequence that can be derived by removing zero or more elements without changing the order of the remaining elements.
For example, for nums = [2,1,0,3] the possible subsequence sums are 0, 1, 2, 3, 4, 5, 6 and their bitwise OR yields 7.
Key Insights
- The brute force approach of enumerating all subsequences is infeasible due to the exponential number of subsequences.
- Instead of generating every sum, analyze each bit position independently.
- For any bit position, if at least one element in nums has that bit, then some subsequence sum will include that bit even if the total sum does not.
- Thus, the final result can be computed as the bitwise OR of the total sum (which is the sum of all array elements) and the bitwise OR of all individual elements.
- Mathematically, answer = (sum(nums)) OR (bitwise OR of nums).
Space and Time Complexity
Time Complexity: O(n), where n is the length of nums (we do two traversals of the array). Space Complexity: O(1), as only a few integer variables are used.
Solution
The solution computes two values:
- totalSum: the sum of all elements in nums.
- orAll: the bitwise OR of all elements in nums.
The final answer is obtained by performing a bitwise OR between totalSum and orAll.
This works because:
- totalSum represents the maximum possible sum (from taking all elements).
- orAll captures all bits that appear in any element.
- Any bit that appears in any element will appear in at least one subsequence sum; hence combining these two captures every bit that could be set in one of the subsequence sums.