Number of Subsequences with Odd Sum Problem
#3247
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 3247.
Given an array nums, return the number of subsequences with an odd sum of elements.
Since the answer may be very large, return it modulo 10^9 + 7.
Example 1:
Input: nums = [1,1,1]
Output: 4
Explanation:
The odd-sum subsequences are: [1, 1, 1], [1, 1, 1], [1, 1, 1], [1, 1, 1].
Example 2:
Input: nums = [1,2,2]
Output: 4
Explanation:
The odd-sum subsequences are: [1, 2, 2], [1, 2, 2], [1, 2, 2], [1, 2, 2].
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^9
Solution
Approach: Dynamic Programming
Let f[0] and f[1] be the numbers of non-empty subsequences so far with an even and an odd sum. For an odd x, adding it to an even-sum subsequence gives an odd sum and vice versa, plus the subsequence [x] itself: f[0] += f[1] and f[1] += f[0] + 1 (both using the old values). For an even x, the parity is unchanged: f[0] = 2 * f[0] + 1 and f[1] = 2 * f[1]. Take everything modulo 10^9 + 7. The answer is f[1].
Complexity: O(n) time, O(1) space, where n is the length of nums.
class Solution:
def subsequenceCount(self, nums: List[int]) -> int:
mod = 10**9 + 7
f = [0] * 2
for x in nums:
if x % 2:
f[0], f[1] = (f[0] + f[1]) % mod, (f[0] + f[1] + 1) % mod
else:
f[0], f[1] = (f[0] + f[0] + 1) % mod, (f[1] + f[1]) % mod
return f[1]