Leetcode #2505: Bitwise OR of All Subsequence Sums
In this guide, we solve Leetcode #2505 Bitwise OR of All Subsequence Sums in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: Yes
- Tags: Bit Manipulation, Brainteaser, Array, Math, Prefix Sum
Intuition
Range queries become simple once we precompute cumulative sums.
We can transform subarray conditions into prefix comparisons.
Approach
Compute prefix sums and use a map to find matching prefixes.
This avoids nested loops while keeping the logic clear.
Steps:
- Compute prefix sums.
- Use a map to find valid ranges.
- Update the answer.
Example
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.
Python Solution
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
Complexity
The time complexity is , where is the length of the array and is the maximum value in the array. The space complexity is O(n).
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.