MediumArraySliding WindowTwo Pointers

Subarray Product Less Than K

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now