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
๐Ÿ›’ Shopping Cart Budget Challenge$10$5$2$6Items on Shelf๐Ÿ›’ CartBudget: $100Total: $50Valid Cart Combinations1. [$10] โ†’ Cost: $10 โœ“2. [$10, $5] โ†’ Cost: $50 โœ“3. [$5] โ†’ Cost: $5 โœ“4. [$5, $2] โ†’ Cost: $10 โœ“5. [$5, $2, $6] โ†’ Cost: $60 โœ“6. [$2] โ†’ Cost: $2 โœ“7. [$2, $6] โ†’ Cost: $12 โœ“8. [$6] โ†’ Cost: $6 โœ“โŒ [$10, $5, $2] โ†’ Cost: $100 (not < $100)Total Valid Combinations: 8
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

n
2n
โš  Quadratic Growth
Space Complexity
O(1)

Only using a few variables to track indices and product

n
2n
โœ“ Linear Space

Constraints

  • 1 โ‰ค nums.length โ‰ค 3 ร— 104
  • 1 โ‰ค nums[i] โ‰ค 1000
  • 0 โ‰ค k โ‰ค 106
  • All elements in nums are positive integers
Asked in
Amazon 45 Google 38 Microsoft 32 Meta 28
42.0K Views
High Frequency
~18 min Avg. Time
1.6K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen