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 K INPUT nums array: 10 idx 0 5 idx 1 2 idx 2 6 idx 3 k = 100 Input Values: nums = [10, 5, 2, 6] k = 100 n = 4 elements Find subarrays with product strictly < k ALGORITHM STEPS 1 Initialize Pointers left=0, right=0, prod=1 2 Expand Window prod *= nums[right] 3 Shrink if prod >= k prod /= nums[left++] 4 Count Subarrays count += right - left + 1 Sliding Window Example: 10 5 2 6 window: prod=50 50 < 100 -- OK! Adds 2 subarrays FINAL RESULT Valid Subarrays (8 total): [10] prod=10 [5] prod=5 [10,5] prod=50 [2] prod=2 [5,2] prod=10 [6] prod=6 [2,6] prod=12 [5,2,6] prod=60 OK OK OK OK OK OK OK OK All products < 100 Output: 8 8 valid subarrays found Time: O(n), Space: O(1) Key Insight: The sliding window technique works because all numbers are positive. When product >= k, shrinking the window (moving left pointer) reduces the product. For each valid window, adding (right - left + 1) counts all subarrays ending at 'right' within that window. TutorialsPoint - Subarray Product Less Than K | Optimal Sliding Window Solution
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