Bitwise OR of All Subsequence Sums - Problem
Bitwise OR of All Subsequence Sums
You are given an integer array
A subsequence is a sequence that can be derived from the original array by removing zero or more elements without changing the order of the remaining elements. For example, from array
Goal: Calculate the sum of each subsequence, then return the bitwise OR of all these sums.
Example: For
• Subsequence
• Subsequence
• Subsequence
• Subsequence
• Result:
You are given an integer array
nums. Your task is to find the bitwise OR of the sums of all possible subsequences in the array.A subsequence is a sequence that can be derived from the original array by removing zero or more elements without changing the order of the remaining elements. For example, from array
[1, 2, 3], the subsequences include [] (empty), [1], [2], [3], [1,2], [1,3], [2,3], and [1,2,3].Goal: Calculate the sum of each subsequence, then return the bitwise OR of all these sums.
Example: For
nums = [1, 2]• Subsequence
[] → sum = 0• Subsequence
[1] → sum = 1• Subsequence
[2] → sum = 2• Subsequence
[1,2] → sum = 3• Result:
0 | 1 | 2 | 3 = 3 Input & Output
example_1.py — Basic Case
$
Input:
[1, 2]
›
Output:
3
💡 Note:
Subsequences and their sums: [] → 0, [1] → 1, [2] → 2, [1,2] → 3. Bitwise OR: 0 | 1 | 2 | 3 = 3
example_2.py — Single Element
$
Input:
[5]
›
Output:
5
💡 Note:
Subsequences and their sums: [] → 0, [5] → 5. Bitwise OR: 0 | 5 = 5
example_3.py — Three Elements
$
Input:
[1, 2, 4]
›
Output:
7
💡 Note:
All possible sums: 0, 1, 2, 3, 4, 5, 6, 7 (from 8 subsequences). Bitwise OR of all these values equals 7
Visualization
Tap to expand
Understanding the Visualization
1
Empty Selection
Start with selecting nothing (sum = 0)
2
Add First Item
Now you can choose nothing or the first item
3
Add Second Item
Each previous choice can now include or exclude the new item
4
OR All Totals
Combine all possible totals using bitwise OR
Key Takeaway
🎯 Key Insight: Instead of generating 2^n subsequences, we build possible sums incrementally. Each new element doubles our sum possibilities, but we only track unique values, making the solution much more efficient than brute force enumeration.
Time & Space Complexity
Time Complexity
O(n × S)
n elements, S unique sums. In worst case S can be O(2^n), but often much smaller
✓ Linear Growth
Space Complexity
O(S)
Storing set of all unique possible subsequence sums
✓ Linear Space
Constraints
- 1 ≤ nums.length ≤ 20
- 1 ≤ nums[i] ≤ 104
- The sum of all elements will not exceed 2 × 105
- Time limit: 2 seconds
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code