Count Subsequences That Move Between Positions
VisaSoftware Engineer · Technical ScreenLast updated
This problem tests dynamic programming skills, specifically the ability to count subsequences that satisfy a positional movement constraint based on element parity.
Problem Statement
You are given an array of n integers. A subsequence is defined as a sequence that can be derived from the array by deleting zero or more elements without changing the order of the remaining elements.
We define a "Valid Alternating Subsequence" as a subsequence where every adjacent pair of elements (a, b) satisfies the condition: (a + b) is odd. In other words, the subsequence must strictly alternate between even and odd numbers.
Your task is to implement a function countValidSubsequences(nums) that returns the total number of non-empty Valid Alternating Subsequences. Since the result can be very large, return it modulo 10^9 + 7.
Function Signature
def countValidSubsequences(nums: list[int]) -> int:
Constraints
1 <= n <= 10^50 <= nums[i] <= 10^9
Examples
Example 1:
Input: nums = [1, 2, 3]
Output: 6
Explanation: The valid subsequences are [1], [2], [3], [1, 2], [2, 3], [1, 2, 3]. Note that [1, 3] is invalid because 1+3 is even.
Example 2:
Input: nums = [2, 4, 6]
Output: 3
Explanation: The only valid subsequences are single-element subsequences: [2], [4], [6].
Edge Cases
- Arrays containing only even or only odd numbers.
- Arrays with duplicate values.
- Large input arrays (ensure
O(n)complexity).
Hints
Hint 1
Consider maintaining two running totals: one for the number of valid subsequences ending in an even number and one for those ending in an odd number.
Hint 2
When you encounter an even number `x`, any odd-ending subsequence can now be extended by `x`, and you can also start a new subsequence consisting only of `x`.
Hint 3
The total count is the sum of both running totals after iterating through the entire array.
Follow-up questions
- How would you modify your approach if the condition was changed to require the subsequence to have a length of at least 3?
- What if the requirement was that the difference between adjacent elements must be exactly 1?
- Can you optimize the space complexity to O(1) if you do not need to store the intermediate counts in an array?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.