Advertisement
Home Data Structure Arrays Count Subarrays Whose Product is Less than K

Count Subarrays Whose Product is Less than K

0
Advertisement

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

  1. If k <= 1, return 0 immediately, because every product of positive integers is at least 1.
  2. Keep a window [left, right] and a running product of the elements inside it, starting at 1.
  3. For each right, multiply product by nums[right].
  4. While product >= k and left <= right, divide product by nums[left] and move left forward.
  5. Every subarray that ends at right and starts anywhere from left to right is valid, so add right - left + 1 to the answer.
  6. After the loop finishes, return the accumulated count.

Java Program

Java
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 than k.
  • product is a long so that multiplying by the next element cannot overflow before we shrink the window.
  • left marks the start of the current valid window, and right is the loop variable that grows it.
  • The inner while loop shrinks the window until the product drops below k. The left <= right check stops it from running past an empty window when a single element is already at least k.
  • right - left + 1 counts every valid subarray ending at right. 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.

rightnums[right]product (after multiply)shrink?left (after)product (after)addedcount
033no0311
1412no01223
2224yes1825
3540yes21027
4110no210310
5660yes (twice)46212

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

Java
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

Java
int[] nums = {1, 2, 3};
int k = 0;
System.out.println(countSubarrays(nums, k));
// Output: 0
// No product of positive integers can be below 1

Example 3: All ones

Java
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 them

Common Mistakes to Avoid

These are the errors learners most often make on this particular problem.

  • Skipping the k <= 1 check – with k = 1 the shrink loop keeps dividing until left passes right, and without the left <= right guard it can read past the window. Return 0 up front.
  • Counting only one subarray per step – adding 1 instead of right - left + 1 gives 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 to k must still shrink the window. Loop while product >= k.
  • Storing the product in an int – values like {50000, 50000} overflow before you shrink and produce a negative product that looks valid. Use a long for product.
  • 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 right emit the slices starting at every index from left to right; 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.