Subarray Product Less Than K
Master this topic with zero to advance depth.
Subarray Product Less Than K
Count the number of contiguous subarrays where the product of all elements is strictly less than k.
Visual Representation
nums = [10, 5, 2, 6], k = 100
[10] -> Prod: 10 (<100) Count +1
[10, 5] -> Prod: 50 (<100) Count +2 (new: [5], [10,5])
[10, 5, 2] -> Prod: 100 (>=100) -> Shrink left
[5, 2] -> Prod: 10 (<100) Count +2 (new: [2], [5,2])
Rule: Subarrays ending at 'right' = right - left + 1Examples
Level I: Brute Force
Intuition
Iterate through every possible starting point i and ending point j. For each pair, calculate the product of elements in nums[i...j]. If the product is less than k, increment the count.
Thought Process
- Outer loop
ifrom0ton-1. - Inner loop
jfromiton-1. - Calculate
prod = prod * nums[j]. - If
prod < k,count++. - If
prod >= k, break inner loop (since elements are positive, product will only increase).
Detailed Dry Run
| i | j | Prod | Result |
|---|---|---|---|
| 0 | 0 (10) | 10 | Count 1 |
| 0 | 1 (5) | 50 | Count 2 |
| 0 | 2 (2) | 100 | STOP |
| 1 | 1 (5) | 5 | Count 3 |
Level II: Log-Sum Prefix Sums + Binary Search (O(N log N))
Intuition
We can transform the product comparison into a sum comparison using logarithms: . Since all elements are positive, the prefix sums of are monotonically increasing, allowing us to use Binary Search for each starting point.
Thought Process
- Precompute an array
prefixLogswhereprefixLogs[i]is the sum oflog(nums[0...i-1]). - For each starting index
i, we need to find the largestjsuch thatprefixLogs[j+1] - prefixLogs[i] < log(K) - epsilon(to handle floating point precision). - The number of such
j's for a fixediisj - i + 1.
Pattern: Logarithmic Transformation
Level III: Optimal (Sliding Window)
Intuition
Thought Process
Standard variable-size sliding window. The key observation is that if a window [left, right] has a product < k, then ALL subarrays ending at right and starting between left and right also have products < k. There are right - left + 1 such subarrays.
Patterns
- Window-based Counting: Add
Right - Left + 1to result. - Product Control: Divide by
nums[left]when product .
Detailed Dry Run
| Right | Num | Product | Left | Count Add | Total |
|---|---|---|---|---|---|
| 0 | 10 | 10 | 0 | 1 | 1 |
| 1 | 5 | 50 | 0 | 2 | 3 |
| 2 | 2 | 100->10 | 1 | 2 | 5 |
| 3 | 6 | 60 | 1 | 3 | 8 |
⚠️ Common Pitfalls & Tips
Edge case k <= 1 is critical because the product of any subarray of positive integers is at least 1, which wouldn't be strictly less than 1.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.