Bitwise OR of All Subsequence Sums Problem
Description
LeetCode Problem 2505.
Given an integer array nums, return the value of the bitwise OR of the sum of all possible subsequences in the array.
A subsequence is a sequence that can be derived from another sequence by removing zero or more elements without changing the order of the remaining elements.
Example 1:
Input: nums = [2,1,0,3]
Output: 7
Explanation: All possible subsequence sums that we can have are: 0, 1, 2, 3, 4, 5, 6.
And we have 0 OR 1 OR 2 OR 3 OR 4 OR 5 OR 6 = 7, so we return 7.
Example 2:
Input: nums = [0,0,0]
Output: 0
Explanation: 0 is the only possible subsequence sum we can have, so we return 0.
Constraints:
1 <= nums.length <= 10^50 <= nums[i] <= 10^9
Solution
Approach: Bit Counting with Carries
Count how many numbers have each bit set. A subset sum has bit i set in its OR whenever some subset sum has bit i set. If at least one number has bit i, picking just that number works. If no number has bit i but the lower bits can carry into it, then a subset exists too: c ones at bit i - 1 can be combined to produce c // 2 ones at bit i.
So walk from the lowest bit up. If cnt[i] > 0, set bit i in the answer. Then push the carry cnt[i] // 2 into cnt[i + 1].
Complexity: O(n log M) time, where M is the largest value, and O(log M) space.
class Solution:
def subsequenceSumOr(self, nums: List[int]) -> int:
cnt = [0] * 64
ans = 0
for v in nums:
for i in range(31):
if (v >> i) & 1:
cnt[i] += 1
for i in range(63):
if cnt[i]:
ans |= 1 << i
cnt[i + 1] += cnt[i] // 2
return ans