The "Subarray Product Less Than K" interview question asks you to count the number of contiguous subarrays whose product is strictly less than a given integer k. For example, given an array of positive integers [10, 5, 2, 6] and k = 100, you need to find all subarrays like [10], [5], [10, 5], etc., that satisfy the condition. This problem is particularly interesting because it deals with products, which can grow very quickly.
This question is a favorite at companies like Apple, Microsoft, and Google because it is a perfect candidate for the sliding window technique. It tests whether a candidate can optimize an O(n^2) brute-force solution down to O(n) time complexity. It also requires careful handling of edge cases, such as when k is 0 or 1, where no product of positive integers can be less than k.
The most efficient pattern for this problem is the Sliding Window (Two Pointers). You maintain a "window" of elements whose product is less than k. As you expand the window by moving the right pointer, you multiply the current product. If the product becomes greater than or equal to k, you shrink the window from the left until the product is back within the limit. For each right pointer position, the number of new valid subarrays added is right - left + 1.
Array: [2, 3, 5], k = 15.
The most common mistake is not correctly counting the subarrays. Many candidates forget that right - left + 1 represents the number of valid subarrays ending at the current right pointer. Another frequent error is failing to handle k <= 1. Since the array contains only positive integers, a product of 1 or more can never be strictly less than 1. Forgetting to check this can lead to an infinite loop or incorrect results.
When practicing the Subarray Product Less Than K interview pattern, focus on the "expansion and contraction" logic of the sliding window. Be ready to explain why the right - left + 1 formula works—it's because adding a new element to a valid window creates exactly that many new subarrays. Also, mention the O(n) time and O(1) space complexity to demonstrate your optimization skills.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Max Consecutive Ones III | Medium | Solve | |
| Minimum Size Subarray Sum | Medium | Solve | |
| Count Subarrays With Score Less Than K | Hard | Solve | |
| Maximum Fruits Harvested After at Most K Steps | Hard | Solve | |
| Maximum Frequency of an Element After Performing Operations I | Medium | Solve |