Title: Count Subarrays Whose Product is Less than K
In this guide, you’ll learn how to count the contiguous subarrays of a positive integer array whose product is strictly less than a given value k. It is a classic interview problem that looks like it needs nested loops, but a clever sliding window solves it in a single pass.
Let’s explore why the window works, how to write it cleanly in Java, and which mistakes trip up most learners. By the end, you will be able to explain the solution, trace it by hand, and handle the follow-up questions interviewers love to ask.
Understanding the Problem
You are given an array nums of positive integers and an integer k. A subarray is a contiguous slice of the array. The task is to return how many subarrays have a product strictly smaller than k.
The brute-force approach checks every pair of start and end indices, which costs O(n²) or even O(n³) if you recompute products. The key observation is that all elements are positive, so adding an element to a subarray can only increase the product, and removing one can only decrease it. That monotonic behavior is exactly what a sliding window needs.
Approach / Algorithm Steps
- If
k <= 1, return 0 immediately, because every product of positive integers is at least 1. - Keep a window
[left, right]and a runningproductof the elements inside it, starting at 1. - For each
right, multiplyproductbynums[right]. - While
product >= kandleft <= right, divideproductbynums[left]and moveleftforward. - Every subarray that ends at
rightand starts anywhere fromlefttorightis valid, so addright - left + 1to the answer. - After the loop finishes, return the accumulated count.
Java Program
public class CountSubarraysProductLessThanK {
public static int countSubarrays(int[] nums, int k) {
if (nums == null || k <= 1) {
return 0;
}
long product = 1;
int left = 0;
int count = 0;
for (int right = 0; right < nums.length; right++) {
product *= nums[right];
while (product >= k && left <= right) {
product /= nums[left];
left++;
}
count += right - left + 1;
}
return count;
}
public static void main(String[] args) {
int[] nums = {10, 5, 2, 6};
int k = 100;
System.out.println(countSubarrays(nums, k));
}
}Explanation of the Program
if (nums == null || k <= 1)guards the null reference and the case where no product can be smaller thank.productis alongso that multiplying by the next element cannot overflow before we shrink the window.leftmarks the start of the current valid window, andrightis the loop variable that grows it.- The inner
whileloop shrinks the window until the product drops belowk. Theleft <= rightcheck stops it from running past an empty window when a single element is already at leastk. right - left + 1counts every valid subarray ending atright. This works because if[left, right]is valid, then every shorter suffix of it is valid too.
Step-by-Step Trace
Let’s trace the algorithm on nums = [3, 4, 2, 5, 1, 6] with k = 20. The expected output is 12.
| right | nums[right] | product (after multiply) | shrink? | left (after) | product (after) | added | count |
|---|---|---|---|---|---|---|---|
| 0 | 3 | 3 | no | 0 | 3 | 1 | 1 |
| 1 | 4 | 12 | no | 0 | 12 | 2 | 3 |
| 2 | 2 | 24 | yes | 1 | 8 | 2 | 5 |
| 3 | 5 | 40 | yes | 2 | 10 | 2 | 7 |
| 4 | 1 | 10 | no | 2 | 10 | 3 | 10 |
| 5 | 6 | 60 | yes (twice) | 4 | 6 | 2 | 12 |
At the end of each iteration, product holds the product of nums[left..right], which is strictly less than k, and count holds the number of valid subarrays ending at or before right.
Examples
Example 1: Several valid windows
int[] nums = {10, 5, 2, 6};
int k = 100;
System.out.println(countSubarrays(nums, k));
// Output: 8
// [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]Example 2: k is too small
int[] nums = {1, 2, 3};
int k = 0;
System.out.println(countSubarrays(nums, k));
// Output: 0
// No product of positive integers can be below 1Example 3: All ones
int[] nums = {1, 1, 1};
int k = 2;
System.out.println(countSubarrays(nums, k));
// Output: 6
// Every subarray has product 1, and there are 3 + 2 + 1 = 6 of themCommon Mistakes to Avoid
These are the errors learners most often make on this particular problem.
- Skipping the k <= 1 check – with
k = 1the shrink loop keeps dividing untilleftpassesright, and without theleft <= rightguard it can read past the window. Return 0 up front. - Counting only one subarray per step – adding 1 instead of
right - left + 1gives 4 instead of 8 on[10, 5, 2, 6]. Add the full window length, since every suffix of the window is valid. - Using < instead of >= in the shrink loop – the problem says strictly less than
k, so a product equal tokmust still shrink the window. Loop whileproduct >= k. - Storing the product in an int – values like
{50000, 50000}overflow before you shrink and produce a negative product that looks valid. Use alongforproduct. - Assuming the array can contain zeros or negatives – the window logic depends on products only growing as you add elements. Confirm the elements are positive before using this approach.
Edge Cases to Test
Run through these inputs before declaring the solution done.
- Empty array
- Single element below k
- Single element equal to or above k
- k equal to 0 or 1
- All elements equal to 1
- Every element greater than or equal to k
- Large values that would overflow an int product
- Null array reference
Additional Considerations
The time complexity is O(n). Each index enters the window once through right and leaves it at most once through left, so the total work across both pointers is at most 2n steps. The space complexity is O(1), since only a few variables are used.
The overflow edge case matters because the product is multiplied in before the window shrinks. With nums[i] up to about 1000 and the window already holding a product below k, a long keeps that intermediate value safe, whereas an int could wrap around to a misleading small number.
Interview Follow-up Questions
Interviewers often extend the base problem in these directions.
- What if you must return the actual subarrays instead of the count? – keep the same window, but for each
rightemit the slices starting at every index fromlefttoright; the output size dominates the cost. - What if the array can contain zeros? – a zero makes every window containing it valid and breaks division, so track the product with a zero counter or split the array at zeros.
- What if you need a sum less than K instead of a product? – the same sliding window works for positive numbers, replacing multiply and divide with add and subtract.
- What if the numbers can be negative? – the monotonic property is gone, so the window fails; consider prefix sums of logarithms with absolute values and sign tracking, or fall back to O(n²).
- What if the input arrives as a stream too large for memory? – the window only needs the elements currently inside it, so buffer them in a deque and process each new element as it arrives, giving O(window size) memory.
Conclusion
Counting subarrays with a product below k becomes simple once you notice that positive numbers make the product monotonic. A two-pointer window gives an O(n) solution, and the right - left + 1 counting trick is the part worth remembering.
Try adapting the code to handle sums, or to return the subarrays themselves. You can learn more about similar problems in our Arrays category.



