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 Sums INPUT Input Array: nums 1 index 0 2 index 1 Array Details nums = [1, 2] Length: 2 Values: positive integers All Subsequences: [], [1], [2], [1,2] Sums: 0, 1, 2, 3 OR: 0|1|2|3 = 3 ALGORITHM STEPS 1 Initialize Set sums = {0} (empty subseq) 2 Process num=1 sums = {0, 0+1} = {0, 1} 3 Process num=2 sums = {0,1,2,3} 4 Compute OR OR all values in set Set Evolution Init: {0} +1: {0, 1} +2: {0, 1, 2, 3} OR: 0|1|2|3 = 3 FINAL RESULT Binary OR Operation 0 = 00 1 = 01 2 = 10 3 = 11 OR = 11 = 3 Output 3 OK - Verified 0 | 1 | 2 | 3 = 3 Key Insight: Use a Set to track all possible subsequence sums. For each number, add it to every existing sum to generate new sums. Finally, OR all sums together. The Set avoids duplicate calculations and the DP approach builds sums incrementally: new_sums = old_sums U {s + num for s in old_sums}. TutorialsPoint - Bitwise OR of All Subsequence Sums | Dynamic Programming with Set
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