Community Problem

Subarray Product Less Than K

Difficulty: Medium

Count contiguous subarrays whose product is strictly less than k, in linear time using a sliding window.

Subarray Product Less Than K

Count contiguous subarrays whose product is strictly less than k, in linear time using a sliding window.

MEDIUM
Free
arrays
sliding-window
two-pointers
yukisantos

By @yukisantos

March 4, 2026

·

Updated May 20, 2026

817 views

13

4.3 (14)

Whoever first wrote this in a real interview deserves a coffee, because it is the cleanest example I know of the "count subarrays ending at right" sliding-window pattern. The official catalog has Subarray Sum Equals K (prefix-sum + hash) and Minimum Size Subarray Sum (window grow-shrink), but it skipped the multiplicative variant where the count of valid windows is exactly right - left + 1 at each step. Once that identity clicks, the algorithm is six lines.

Subarray Product Less Than K

Given an array of positive integers nums and an integer k, return the number of contiguous subarrays whose product of all elements is strictly less than k.

Examples

Example 1:

  • Input: nums = [10, 5, 2, 6], k = 100
  • Output: 8
  • Explanation: The 8 subarrays with product less than 100 are [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6]. Note [10, 5, 2] has product 100 which is NOT strictly less than 100.

Example 2:

  • Input: nums = [1, 2, 3], k = 0
  • Output: 0
  • Explanation: All products are at least 1 (the array is positive), so none are less than 0.

Example 3:

  • Input: nums = [1, 1, 1], k = 2
  • Output: 6
  • Explanation: Every contiguous subarray has product 1 which is less than 2. With n = 3 there are 3 + 2 + 1 = 6 contiguous subarrays.

Example 4:

  • Input: nums = [10, 9, 10, 4, 3, 8, 3, 3, 6, 2, 10, 10, 9, 3], k = 19
  • Output: 18
  • Explanation: A larger mixed input; the canonical answer is 18.

Constraints

  • 1 <= nums.length <= 3 * 10^4
  • 1 <= nums[i] <= 1000
  • 0 <= k <= 10^6

Follow-up

If k <= 1, the answer is always 0 because every product of positive integers is at least 1. Make sure your sliding window handles that boundary correctly (the inner shrink loop should not run forever).

Solution

Hints

0/4
Hint 1
Hint 2
Hint 3
Hint 4
All Problems