Number of Subsequences with Odd Sum - Problem

Given an array nums, return the number of subsequences with an odd sum of elements.

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.

Since the answer may be very large, return it modulo 109 + 7.

Input & Output

Example 1 — All Odd Numbers
$ Input: nums = [1,3,5]
Output: 4
💡 Note: The subsequences with odd sums are [1], [3], [5], [1,3,5]. Sums are 1, 3, 5, 9 respectively - all odd. Total count = 4.
Example 2 — Mixed Odd and Even
$ Input: nums = [2,4,6]
Output: 0
💡 Note: All numbers are even, so any sum will be even. No subsequences can have odd sums. Total count = 0.
Example 3 — Single Odd Element
$ Input: nums = [1,2,4]
Output: 4
💡 Note: Subsequences with odd sums: [1] (sum=1), [1,2] (sum=3), [1,4] (sum=5), [1,2,4] (sum=7). All contain the single odd number 1. Total count = 4.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • Answer is returned modulo 109 + 7

Visualization

Tap to expand
Subsequences with Odd Sum INPUT Array: nums 1 odd 3 odd 5 odd [0] [1] [2] Total subsequences: 2^3 = 8 (excluding empty set: 7) All Subsequences: [1]=1 [3]=3 [5]=5 [1,3]=4 [1,5]=6 [3,5]=8 [1,3,5]=9 ALGORITHM STEPS 1 Count Odd/Even oddCount=3, evenCount=0 2 Initialize DP oddSum=0, evenSum=1 3 Iterate Elements Update odd/even counts 4 Return Result Return oddSum % (10^9+7) DP Transition Table: Elem oddSum evenSum init 0 1 1 1 1 3 2 2 5 4 4 FINAL RESULT Odd Sum Subsequences: [1] --> sum = 1 (odd) OK [3] --> sum = 3 (odd) OK [5] --> sum = 5 (odd) OK [1,3,5] --> sum = 9 (odd) OK Even sum (excluded): [1,3]=4, [1,5]=6, [3,5]=8 OUTPUT 4 4 subsequences with odd sum Key Insight: For each element, track counts of subsequences with odd and even sums. When adding an odd number, odd+odd=even and even+odd=odd. Use DP: newOdd = oldOdd + oldEven, newEven = oldEven + oldOdd. Time: O(n), Space: O(1). Apply modulo 10^9+7 to handle large results. TutorialsPoint - Number of Subsequences with Odd Sum | Optimal DP Solution
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.5K Views
Medium Frequency
~25 min Avg. Time
847 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