KatInterview

Count Parity-Alternating Subsequences

Dynamic ProgrammingAuto-graded · 22 test cases
HardAuto-gradedDynamic Programmingdynamic-programmingsubsequencesparity

Last updated

Tests dynamic programming with state tracking to count subsequences where consecutive elements alternate between even and odd values.

You are given an array of integers. Your task is to count how many non-empty subsequences exist where every pair of consecutive elements has opposite parity (one even, one odd).

A subsequence is formed by selecting elements from the array in their original order, possibly skipping some elements. For a subsequence to be valid, whenever two elements appear consecutively in the subsequence, one must be even and the other must be odd.

Single-element subsequences are always valid since they have no consecutive pairs.

Implement a function that counts all such valid subsequences. Since the count can be extremely large, return the result modulo 10^9 + 7.

Constraints

  • 1 <= len(nums) <= 10^5
  • 0 <= nums[i] <= 10^9
  • Subsequences are distinguished by the positions of their elements, not their values
  • The result must be computed modulo 10^9 + 7

Examples

Example 1

Input: count_valid_subsequences([1, 2, 3])

Output: 6

Example 2

Input: count_valid_subsequences([2, 4, 6])

Output: 3

Hints

Hint 1

Track the count of valid subsequences based on the parity of their last element

Hint 2

When processing a new element, consider both starting a new single-element subsequence and extending existing subsequences with opposite parity

Hint 3

The state only depends on aggregate counts, not individual subsequence details, allowing constant space optimization