Counting Sequences to K

You receive a list of integers called nums and a target integer k. You begin with a running total val set to 1 and evaluate the numbers in nums sequentially. For every element at index i, you have three options to update your running total:

  • Multiply val by nums[i].
  • Divide val by nums[i].
  • Do nothing to val.

Division operates perfectly rationally (e.g., 1 / 2 remains a fraction). After going through the entire list, check if the final rational value of val perfectly matches k. Determine and return the total number of unique operation sequences that lead exactly to k.

Example 1:

Input: nums = [2, 3, 6], k = 1

Output: 3

Explanation: We can achieve a final rational value of 1 in exactly three ways. The simplest sequence is to leave the value unchanged for all three elements. Alternatively, we can multiply the starting 1 by 2, multiply it by 3 (reaching 6), and then divide by the final 6 to return to 1. The third valid sequence is the exact inverse: divide by 2, divide by 3 (reaching 1/6), and then multiply by 6. This results in exactly 3 valid sequences.

Example 2:

Input: nums = [4, 4], k = 16

Output: 1

Explanation: To reach a target value of 16 starting from an initial value of 1, we are mathematically forced to maximize our operations. The only valid sequence is to multiply by the first 4 (giving 4) and then multiply by the second 4 (giving 16). Any sequence involving a division or a skip operation would inevitably leave the final rational value strictly less than 16, meaning there is only 1 valid sequence.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [5, 2, 2], k = 5

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 19
  • 1 <= nums[i] <= 6
  • 1 <= k <= 1015

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
// --- IDE Code ---
class Solution {
public:
int countSequences(vector<int>& nums, long long k) {
// Write your code here
return 0;
}
};
Test Case

Input:

K
Nums