LeetCode 0713. Subarray Product Less Than K Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
0713. Subarray Product Less Than K

Description

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.

 

Example 1:

Input: nums = [10,5,2,6], k = 100
Output: 8
Explanation: The 8 subarrays that have product less than 100 are:
[10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]
Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.

Example 2:

Input: nums = [1,2,3], k = 0
Output: 0

 

Constraints:

  • 1 <= nums.length <= 3 * 104
  • 1 <= nums[i] <= 1000
  • 0 <= k <= 106

Solutions

Solution 1: Two Pointers

We can use two pointers to maintain a sliding window, where the product of all elements in the window is less than k.

Define two pointers l and r pointing to the left and right boundaries of the sliding window, initially l = r = 0. We use a variable p to record the product of all elements in the window, initially p = 1.

Each time, we move r one step to the right, adding the element x pointed to by r to the window, and update p = p × x. Then, if p ≥ k, we move l one step to the right in a loop and update p = p ÷ nums[l] until p < k or l \gt r. Thus, the number of contiguous subarrays ending at r with a product less than k is r - l + 1. We then add this number to the answer and continue moving r until r reaches the end of the array.

The time complexity is O(n), where n is the length of the array. The space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptKotlinC#
class Solution: def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int: ans = l = 0 p = 1 for r, x in enumerate(nums): p *= x while l <= r and p >= k: p //= nums[l] l += 1 ans += r - l + 1 return ans(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !