#713
Subarray Product Less Than K
MediumArrayBinary SearchSliding WindowPrefix SumSliding WindowTwo Pointers
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a sliding window approach to maintain a product of the current subarray. This allows us to efficiently count valid subarrays without recalculating products from scratch.
⚙️
Algorithm
4 steps- 1Step 1: Initialize two pointers (left and right) and a product variable to 1.
- 2Step 2: Expand the right pointer to include elements in the product until it reaches or exceeds k.
- 3Step 3: For each position of the right pointer, count how many subarrays end at right and start from left to right.
- 4Step 4: If the product exceeds k, move the left pointer to reduce the product.
solution.py11 lines
1def numSubarrayProductLessThanK(nums, k):
2 count = 0
3 left = 0
4 product = 1
5 for right in range(len(nums)):
6 product *= nums[right]
7 while left <= right and product >= k:
8 product //= nums[left]
9 left += 1
10 count += right - left + 1
11 return countℹ
Complexity note: The time complexity is O(n) because each element is processed at most twice (once by the right pointer and once by the left pointer). The space complexity is O(1) since we only use a few variables for counting and tracking indices.
- 1Using a sliding window allows for efficient counting of subarrays without recalculating products from scratch.
- 2The relationship between the left and right pointers helps maintain the product under the constraint.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.