Bitwise OR of All Subsequence Sums - Problem

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.

For example, given array [1, 2, 3], the subsequences are: [] (sum=0), [1] (sum=1), [2] (sum=2), [3] (sum=3), [1,2] (sum=3), [1,3] (sum=4), [2,3] (sum=5), [1,2,3] (sum=6). The bitwise OR of all these sums is 0 | 1 | 2 | 3 | 3 | 4 | 5 | 6 = 7.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1, 2]
Output: 3
💡 Note: Subsequences: [] (sum=0), [1] (sum=1), [2] (sum=2), [1,2] (sum=3). OR of sums: 0 | 1 | 2 | 3 = 3
Example 2 — Single Element
$ Input: nums = [5]
Output: 5
💡 Note: Subsequences: [] (sum=0), [5] (sum=5). OR of sums: 0 | 5 = 5
Example 3 — Three Elements
$ Input: nums = [1, 2, 4]
Output: 7
💡 Note: All possible sums: 0,1,2,3,4,5,6,7. OR of all sums: 0|1|2|3|4|5|6|7 = 7

Constraints

  • 1 ≤ nums.length ≤ 20
  • 1 ≤ nums[i] ≤ 105

Visualization

Tap to expand
Bitwise OR of All Subsequence Sums12Input: [1, 2][] → 0[1] → 1[2] → 2[1,2] → 3All Subsequences0 | 1 | 2 | 3= 3Final Result
Understanding the Visualization
1
Input
Array [1, 2] with all possible subsequences
2
Calculate Sums
Find sum of each subsequence: 0, 1, 2, 3
3
Bitwise OR
OR all sums together: 0 | 1 | 2 | 3 = 3
Key Takeaway
🎯 Key Insight: The bitwise OR captures all bit positions that can be set by any possible subsequence sum
Asked in
Google 15 Meta 12 Microsoft 8
23.0K Views
Medium Frequency
~25 min Avg. Time
850 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen