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
๐ŸŽญ The Parity Magic ShowEmpty BagEven: 1Odd: 0Add 1 (odd)Flip!Even: 1Odd: 1Add 3 (odd)Flip!Even: 1Odd: 2Add 5 (odd)Flip!Even: 1Odd: 4The Magic Rules๐Ÿ”ฎ Odd Number (Flip Spell):โ€ข Transforms all even sums โ†’ odd sumsโ€ข Transforms all odd sums โ†’ even sumsโœจ Even Number (Duplicate Spell):โ€ข Doubles the count of even sumsโ€ข Doubles the count of odd sums๐ŸŽฏ Final Result: Count of odd sums = 4
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!
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
32.4K Views
Medium Frequency
~15 min Avg. Time
890 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