713. Subarray Product Less Than K LeetCode Solution

In this guide, you will get 713. Subarray Product Less Than K LeetCode Solution with the best time and space complexity. The solution to Subarray Product Less Than K problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Subarray Product Less Than K solution in C++
  4. Subarray Product Less Than K solution in Java
  5. Subarray Product Less Than K solution in Python
  6. Additional Resources
713. Subarray Product Less Than K LeetCode Solution image

Problem Statement of Subarray Product Less Than K

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

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(1)

713. Subarray Product Less Than K LeetCode Solution in C++

class Solution {
 public:
  int numSubarrayProductLessThanK(vector<int>& nums, int k) {
    if (k <= 1)
      return 0;

    int ans = 0;
    int prod = 1;

    for (int l = 0, r = 0; r < nums.size(); ++r) {
      prod *= nums[r];
      while (prod >= k)
        prod /= nums[l++];
      ans += r - l + 1;
    }

    return ans;
  }
};
/* code provided by PROGIEZ */

713. Subarray Product Less Than K LeetCode Solution in Java

class Solution {
  public int numSubarrayProductLessThanK(int[] nums, int k) {
    if (k <= 1)
      return 0;

    int ans = 0;
    int prod = 1;

    for (int l = 0, r = 0; r < nums.length; ++r) {
      prod *= nums[r];
      while (prod >= k)
        prod /= nums[l++];
      ans += r - l + 1;
    }

    return ans;
  }
}
// code provided by PROGIEZ

713. Subarray Product Less Than K LeetCode Solution in Python

class Solution:
  def numSubarrayProductLessThanK(self, nums: list[int], k: int) -> int:
    if k <= 1:
      return 0

    ans = 0
    prod = 1

    j = 0
    for i, num in enumerate(nums):
      prod *= num
      while prod >= k:
        prod /= nums[j]
        j += 1
      ans += i - j + 1

    return ans
# code by PROGIEZ

Additional Resources

See also  404. Sum of Left Leaves LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.