MediumArraySliding WindowTwo Pointers

1 approach, code in every language

Problem description

Given an array of positive integers and a threshold k, count how many contiguous slices of the array have a product of all their elements strictly below k.

Since every value is positive, extending a window can only grow the product and shrinking it can only reduce the product. That monotonic behavior means a sliding window can maintain the running product and, whenever it grows too large, slide the left edge forward until the window is valid again.

Example 1

Input: nums = [10,5,2,6], k = 100

Output: 8

The valid contiguous slices are [10], [5], [2], [6], [10,5], [5,2], [2,6], and [5,2,6]. The slice [10,5,2] is excluded because 100 is not strictly less than 100.

Example 2

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

Output: 0

No product of positive integers can be below 0, so nothing qualifies.

Constraints

  • 1 ≤ nums.length ≤ 3 × 10^4
  • 1 ≤ nums[i] ≤ 10^3
  • 0 ≤ k ≤ 10^6

After the pattern

Now solve one you haven't seen.

Safe Stretches of the Filter Cascade is our own problem on the technique behind Subarray Product Less Than K: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free