Subarray Product Less Than K - Problem
Given an array of positive integers nums and an integer k, your task is to find the number of contiguous subarrays where the product of all elements in the subarray is strictly less than k.
A subarray is a contiguous sequence of elements within an array. For example, in array [1, 2, 3, 4], some subarrays include [1], [2, 3], [1, 2, 3], etc.
Key Points:
- All numbers in the array are positive integers
- We're looking for subarrays where the product (not sum) is less than k
- The product must be strictly less than k (not equal to k)
- Return the count of such subarrays, not the subarrays themselves
Input & Output
example_1.py โ Basic Case
$
Input:
nums = [10, 5, 2, 6], k = 100
โบ
Output:
8
๐ก Note:
The 8 subarrays with product less than 100 are: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]. Note that [10,5,2] has product 100 which is not strictly less than k.
example_2.py โ Single Element
$
Input:
nums = [1, 2, 3], k = 0
โบ
Output:
0
๐ก Note:
Since k = 0, no subarray can have a product strictly less than 0 (all elements are positive).
example_3.py โ All Elements Valid
$
Input:
nums = [1, 1, 1], k = 2
โบ
Output:
6
๐ก Note:
All possible subarrays have product 1 < 2: [1], [1], [1], [1,1], [1,1], [1,1,1]. Total = 6.
Visualization
Tap to expand
Understanding the Visualization
1
Start Shopping
Begin with an empty cart (left = right = 0)
2
Add Items
Add items to cart (expand window) while total cost < k
3
Remove Items
When over budget, remove items from left side of cart
4
Count Combinations
For each valid cart state, count all possible subcombinations
Key Takeaway
๐ฏ Key Insight: Use sliding window technique where each valid window of size n contributes n new subarrays, achieving O(n) efficiency instead of O(nยฒ) brute force.
Time & Space Complexity
Time Complexity
O(nยฒ)
Two nested loops: outer loop runs n times, inner loop runs up to n times
โ Quadratic Growth
Space Complexity
O(1)
Only using a few variables to track indices and product
โ Linear Space
Constraints
- 1 โค nums.length โค 3 ร 104
- 1 โค nums[i] โค 1000
- 0 โค k โค 106
- All elements in nums are positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code