Count Sequences to K Problem
Description
LeetCode Problem 3850.
You are given an integer array nums, and an integer k.
Start with an initial value val = 1 and process nums from left to right. At each index i, you must choose exactly one of the following actions:
- Multiply
valbynums[i]. - Divide
valbynums[i]. - Leave
valunchanged.
After processing all elements, val is considered equal to k only if its final rational value exactly equals k.
Return the count of distinct sequences of choices that result in val == k.
Note: Division is rational (exact), not integer division. For example, 2 / 4 = 1 / 2.
Example 1:
Input: nums = [2,3,2], k = 6
Output: 2
Explanation:
The following 2 distinct sequences of choices result in val == k:
Sequence Operation on nums[0] Operation on nums[1] Operation on nums[2] Final val
1 Multiply: val = 1 * 2 = 2 Multiply: val = 2 * 3 = 6 Leave val unchanged 6
2 Leave val unchanged Multiply: val = 1 * 3 = 3 Multiply: val = 3 * 2 = 6 6
Example 2:
Input: nums = [4,6,3], k = 2
Output: 2
Explanation:
The following 2 distinct sequences of choices result in val == k:
Sequence Operation on nums[0] Operation on nums[1] Operation on nums[2] Final val
1 Multiply: val = 1 * 4 = 4 Divide: val = 4 / 6 = 2 / 3 Multiply: val = (2 / 3) * 3 = 2 2
2 Leave val unchanged Multiply: val = 1 * 6 = 6 Divide: val = 6 / 3 = 2 2
Example 3:
Input: nums = [1,5], k = 1
Output: 3
Explanation:
The following 3 distinct sequences of choices result in val == k:
Sequence Operation on nums[0] Operation on nums[1] Final val
1 Multiply: val = 1 * 1 = 1 Leave val unchanged 1
2 Divide: val = 1 / 1 = 1 Leave val unchanged 1
3 Leave val unchanged Leave val unchanged 1
Constraints:
1 <= nums.length <= 191 <= nums[i] <= 61 <= k <= 10^15
Solution
Approach: Memoized Search
Let dfs(i, p, q) be the number of ways to handle nums[i..] when the current value is the fraction p / q. We start at dfs(0, 1, 1). Every element has three choices: leave the value alone, multiply by nums[i], or divide by nums[i].
To keep the numbers small we always reduce the fraction by the gcd after multiplying or dividing. At the end (i == n) the sequence counts when the fraction equals exactly k, that is p == k and q == 1. Results are cached by (i, p, q); since each nums[i] is at most 6, only a limited number of fractions can appear.
Complexity: about O(n4) states (only a few distinct fractions are reachable) and the same memory.
from math import gcd
from functools import lru_cache
class Solution:
def countSequences(self, nums: List[int], k: int) -> int:
@lru_cache(None)
def dfs(i: int, p: int, q: int) -> int:
if i == n:
return 1 if p == k and q == 1 else 0
x = nums[i]
res = dfs(i + 1, p, q)
g = gcd(p * x, q)
res += dfs(i + 1, p * x // g, q // g)
g = gcd(p, q * x)
res += dfs(i + 1, p // g, q * x // g)
return res
n = len(nums)
ans = dfs(0, 1, 1)
dfs.cache_clear()
return ans