Subarray Product Less Than K

Medium · Sliding Window · Array · Sliding Window · Two Pointers

Problem

Given an array of positive integers nums and an integer k, return how many contiguous subarrays have a product of all their elements strictly less than k.

Every subarray is counted by its position, so equal subarrays at different places count separately, and a single element is a subarray too.

Examples

Input: nums = [2,5,3,10], k = 30
Output: 6

The qualifying subarrays are [2], [5], [3], [10], [2,5] and [5,3].

Input: nums = [4,1,1], k = 5
Output: 6

Every subarray has product 4 or 1, both below 5.

Input: nums = [7,8], k = 1
Output: 0

Every product is at least 1, so none is below 1.

Constraints

Approaches

Follow-up

With zeros or negative numbers allowed, the product is no longer monotone and the window breaks. Then you can split at zeros and track signs, or work with prefix sums of logarithms and binary search, which is exact only up to floating-point error.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…