1296. Exact Product Stretches

Medium3.5 points estimatedSliding WindowTwo PointersMathsArray

An assembly line applies a sequence of positive integer scaling factors, given in the array nums. A run of consecutive factors combines into one factor by multiplying them together. Given k, count how many non-empty contiguous runs have a combined product exactly equal to k. Since every factor is at least 1, a product never shrinks as a run grows, so you can count the runs whose product is at most k, subtract the runs whose product is at most k - 1, and compute each count with a shrinking window. Return the count as a 64-bit integer, because with 200000 factors it can pass 32 bits. Target O(n) time and O(1) extra space.

Example 1

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

The runs [2, 3], [2, 3, 1], [1, 6] and [6] all multiply to 6, giving 4.

Example 2

Input:
nums = [1,1,1], k = 1
Output:
6
Explanation:

Every one of the six runs of three ones multiplies to 1, giving 6.

Example 3

Input:
nums = [5,7], k = 3
Output:
0
Explanation:

The products are 5, 7 and 35, none of which is 3, so the answer is 0.

Constraints

1 ≤ n ≤ 2*105

1 ≤ nums[i] ≤ 1000

1 ≤ k ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…