You are given a list of positive whole numbers, nums, and a number k.
Count the contiguous subarrays whose product (all their elements multiplied together) is strictly smaller than k. Subarrays at different positions count separately, even if they hold the same values.
Example 1
Input: nums = [4, 3, 5, 2], k = 30 Output: 7 Why: the four singles, [4, 3], [3, 5] and [5, 2]; [3, 5, 2] is exactly 30
2 more examples and the constraints
Example 2
Input: nums = [2, 7], k = 1 Output: 0 Why: every product is at least 1, so none is below 1
Example 3
Input: nums = [1, 1, 1], k = 2 Output: 6 Why: every one of the 6 subarrays has product 1
Constraints
- 1 ≤ length of nums ≤ 30,000
- 1 ≤ nums[i] ≤ 1,000
- 0 ≤ k ≤ 1,000,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Every start, extendO(n²)
- Sliding windowO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 ones and k = 2 | Verdict |
|---|---|---|---|
| Every start, extend | O(n²) | Fine for small inputs only | |
| Sliding window | O(n) | Best; one pass |
n = length of nums.
Edge cases to test
- k is 0 or 1. No product of positive numbers is below 1, so the answer is 0.
- Exactly k. A product equal to k does not count: [3, 5, 2] with k = 30 is left out.
- A single number too big. [50, 2] with k = 10: the window shrinks to empty around 50 and only [2] counts.
- All ones. [1, 1, 1] with k = 2 counts every subarray: n(n + 1) / 2 = 6.
Common mistakes
- Leaving out the k ≤ 1 guard, so the shrink loop runs left past right.
- Using ≤ instead of <, which counts products equal to k.
- Adding 1 per step instead of right − left + 1, which counts only the longest window.
How to talk through it
- 1Clarify. Are all numbers positive? Is the limit strict? Can k be 0?
- 2Give the brute force. Every start, extend while the product is below k: O(n²) for a list of ones.
- 3Spot the monotone product. Positive numbers mean the product only grows, so a window can slide.
- 4Code the window. Multiply in at right, divide out at left, add right − left + 1 each step.
- 5Test out loud. Run k = 1, a product exactly equal to k and a list of ones before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?