Count Subarrays With Product Equal to K
Problem statement
You are given an array of positive integers nums and a positive integer k.
A subarray is a contiguous, non-empty part of nums. Return the number of subarrays whose product of all elements is exactly k.
Subarrays that cover different index ranges are counted separately, even when they hold the same values.
Function
countProductSubarrays(nums: int[], k: int) → intExamples
Example 1
nums = [2,3,1,6,1]k = 6return = 6The subarrays whose product is exactly 6 are:
[2,3]and[2,3,1], since2 * 3 = 6and multiplying by1changes nothing.[6],[1,6],[6,1]and[1,6,1].
Any other subarray multiplies to something else, for example [3,1,6] gives 18. The answer is 6.
Example 2
nums = [1,1,1]k = 1return = 6Every product is 1, so all 6 subarrays count: three of length 1, two of length 2 and one of length 3.
Example 3
nums = [4,5,10]k = 3return = 0Every value is larger than 3, so every product is larger than 3. The answer is 0.
Constraints
1 <= nums.length <= 3 * 10^41 <= nums[i] <= 10001 <= k <= 10^6