Subarray Product Less Than K - Problem

Given an array of integers nums and an integer k, return the number of contiguous subarrays where the product of all the elements in the subarray is strictly less than k.

Note: Since the product can grow very large, you need to consider edge cases like zeros and negative numbers.

Input & Output

Example 1 — Basic Case
$ Input: nums = [10,5,2,6], k = 100
Output: 8
💡 Note: Valid subarrays: [10], [5], [2], [6], [10,5], [5,2], [2,6], [5,2,6]. Each has product < 100.
Example 2 — All Valid
$ Input: nums = [1,2,3], k = 0
Output: 0
💡 Note: Since k=0, no subarray can have product < 0 (all elements are positive).
Example 3 — Large k
$ Input: nums = [1,1,1], k = 10
Output: 6
💡 Note: All possible subarrays: [1], [1], [1], [1,1], [1,1], [1,1,1]. All have product 1 < 10.

Constraints

  • 1 ≤ nums.length ≤ 3 × 104
  • 1 ≤ nums[i] ≤ 1000
  • 0 ≤ k ≤ 106

Visualization

Tap to expand
Subarray Product Less Than K10526k = 100 (threshold)Valid subarrays (product < 100):[10]=10, [5]=5, [2]=2, [6]=6, [10,5]=50, [5,2]=10, [2,6]=12, [5,2,6]=60Invalid: [10,5,2]=100, [10,5,2,6]=600Result: 8 valid subarrays
Understanding the Visualization
1
Input
Array nums=[10,5,2,6] and threshold k=100
2
Process
Find all contiguous subarrays with product < k
3
Output
Count of valid subarrays = 8
Key Takeaway
🎯 Key Insight: Use sliding window technique - when window [left,right] is valid, all subarrays ending at right are also valid
Asked in
Facebook 25 Amazon 18 Google 15
85.0K Views
Medium Frequency
~15 min Avg. Time
2.1K 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