Number of Subsequences with Odd Sum - Problem
Given an array nums of integers, your task is to find the number of subsequences that have an odd sum.
A subsequence is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements. For example, from array [1,2,3], the subsequences include [1], [2], [1,3], [1,2,3], etc.
The sum is considered odd if it's not divisible by 2. Since the answer can be very large, return it modulo 109 + 7.
Example: For nums = [1,3,5], the subsequences with odd sums are: [1], [3], [5], [1,3], [1,5], [3,5], [1,3,5] โ Answer: 7
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [1,3,5]
โบ
Output:
4
๐ก Note:
All elements are odd. Subsequences with odd sums: [1], [3], [5], [1,3,5]. Note that [1,3] has sum 4 (even), [1,5] has sum 6 (even), [3,5] has sum 8 (even).
example_2.py โ Mixed Even/Odd
$
Input:
nums = [2,4,3]
โบ
Output:
4
๐ก Note:
Subsequences with odd sums: [3], [2,3], [4,3], [2,4,3]. The even numbers [2] and [4] don't contribute to odd sums alone, but can be combined with [3].
example_3.py โ All Even
$
Input:
nums = [2,4,6]
โบ
Output:
0
๐ก Note:
All elements are even, so any subsequence sum will be even. No subsequences have odd sums.
Constraints
- 1 โค nums.length โค 105
- 1 โค nums[i] โค 109
- Answer fits in 32-bit integer after modulo operation
Visualization
Tap to expand
Understanding the Visualization
1
Start with Magic Bag
Begin with an empty bag (even sum = 0). You have 1 way to make an even sum, 0 ways for odd.
2
Cast Odd Spell
When you encounter an odd number, it's a 'flip spell' - all your even sums become odd, and vice versa.
3
Cast Even Spell
When you encounter an even number, it's a 'duplicate spell' - you can add it to any existing subsequence without changing parity.
4
Count Final Odd Sums
After processing all numbers, count how many ways you can create odd sums.
Key Takeaway
๐ฏ Key Insight: Each odd number acts as a 'parity flipper' while even numbers are 'multipliers'. By tracking even/odd counts separately, we can solve this in O(n) time without generating all subsequences!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code