|
| 1 | +''' |
| 2 | + Given an array of integers nums and an integer k, |
| 3 | + return the number of contiguous subarrays where the product of all the elements in the subarray is |
| 4 | + strictly less than k. |
| 5 | +
|
| 6 | + The provided code defines a Java class Solution with a method numSubarrayProductLessThanK that counts the number |
| 7 | + of subarrays in an input array nums whose product is less than a given threshold k. It uses a sliding window |
| 8 | + approach to efficiently compute this count. |
| 9 | +
|
| 10 | + Time Complexity: |
| 11 | +
|
| 12 | + The code iterates through the nums array once, using two pointers (startWindow and endWindow) to define the |
| 13 | + sliding window. This results in a time complexity of O(N), where N is the length of the input array nums. |
| 14 | + Space Complexity: |
| 15 | +
|
| 16 | + The code uses a constant amount of additional space to store integer variables (startWindow, product, and count). |
| 17 | + Therefore, the space complexity is O(1), which means it is independent of the size of the input array. |
| 18 | +''' |
| 19 | +from typing import List |
| 20 | + |
| 21 | +class Solution: |
| 22 | + def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: |
| 23 | + startWindow = 0 # The left end of the sliding window |
| 24 | + product = 1 # Initialize product to 1 to accumulate the product |
| 25 | + count = 0 # Count of subarrays with a product less than k |
| 26 | + |
| 27 | + # Iterate through the list using a sliding window approach |
| 28 | + for endWindow in range(len(nums)): |
| 29 | + # Multiply the current element to the product |
| 30 | + product *= nums[endWindow] |
| 31 | + |
| 32 | + # Shrink the window by moving the start pointer as long as the product is greater than or equal to k |
| 33 | + while startWindow <= endWindow and product >= k: |
| 34 | + # Divide the product by the element at the start of the window |
| 35 | + product /= nums[startWindow] |
| 36 | + # Move the start of the window to the right |
| 37 | + startWindow += 1 |
| 38 | + |
| 39 | + # Update the count with the number of valid subarrays within the current window |
| 40 | + count += endWindow - startWindow + 1 |
| 41 | + |
| 42 | + # Return the count, which represents the number of subarrays with a product less than k |
| 43 | + return count |
0 commit comments