Count Valid Sequences Problem
Description
LeetCode Problem 4002.
You are given two positive integers n and k.
A valid sequence is a sequence of k positive integers such that:
- The sum of all integers in the sequence is equal to
n. - The product of all integers in the sequence is even.
Return the number of valid sequences. Since the answer may be very large, return it modulo 10^9 + 7.
Two sequences are considered different if they differ at any index. For example, [1, 1, 2] and [1, 2, 1] are considered different sequences.
Example 1:
Input: n = 5, k = 3
Output: 3
Explanation:
The sequences of length k = 3 whose sum is 5 are:
Sequence Product Parity
[1, 1, 3] 1 * 1 * 3 = 3 Odd
[1, 2, 2] 1 * 2 * 2 = 4 Even
[2, 1, 2] 2 * 1 * 2 = 4 Even
[2, 2, 1] 2 * 2 * 1 = 4 Even
[1, 3, 1] 1 * 3 * 1 = 3 Odd
[3, 1, 1] 3 * 1 * 1 = 3 Odd
There are 3 sequences with an even product, thus the answer is 3.
Example 2:
Input: n = 3, k = 2
Output: 2
Explanation:
The sequences of length k = 2 whose sum is 3 are:
Sequence Product Parity
[1, 2] 1 * 2 = 2 Even
[2, 1] 2 * 1 = 2 Even
There are 2 sequences with an even product, thus the answer is 2.
Example 3:
Input: n = 5, k = 5
Output: 0
Explanation:
The only possible sequence of length k = 5 whose sum is 5 is [1, 1, 1, 1, 1], which has an odd product. Thus, the answer is 0.
Constraints:
1 <= n <= 5 * 10^51 <= k <= n
Solution
Approach: Combinatorics
The number of ordered ways to write n as a sum of k positive integers is C(n-1, k-1) (stars and bars). The product is even when at least one number is even, so we subtract the sequences where every number is odd.
Write each odd number as 2a + 1 with a >= 0. Then the sum condition becomes a_1 + ... + a_k = (n - k) / 2. This has a solution only when n + k is even, and then the number of all-odd sequences is C((n + k) / 2 - 1, k - 1); otherwise there are none.
So the answer is C(n-1, k-1) - C((n+k)/2 - 1, k-1) (the second term only when n + k is even), modulo 10^9 + 7. Precompute factorials up to n and get each binomial with a modular inverse from Fermat's little theorem.
Complexity: time O(n), space O(n).
MOD = 10**9 + 7
class Solution:
def countValidSequences(self, n: int, k: int) -> int:
f = [1] * (n + 1)
for i in range(1, n + 1):
f[i] = f[i - 1] * i % MOD
def comb(a: int, b: int) -> int:
return f[a] * pow(f[b] * f[a - b] % MOD, MOD - 2, MOD) % MOD
ans = comb(n - 1, k - 1)
if (n + k) % 2 == 0:
ans = (ans - comb((n + k) // 2 - 1, k - 1)) % MOD
return ans