Subarray Product Less Than K
Problem Statement
You are given an array of positive integers nums and an integer k.
Count how many contiguous subarrays have a product of all their elements that is strictly less than k.
An integer array nums (every element ≥ 1) and an integer k.
The number of subarrays whose product is < k.
The 8 subarrays are [10], [5], [2], [6], [10, 5], [5, 2], [2, 6] and [5, 2, 6]. [10, 5, 2] has product exactly 100, which is not strictly less than 100.
Every product is at least 1, so no product can be less than 0.
- • 1 ≤ nums.length ≤ 3·10^4
- • 1 ≤ nums[i] ≤ 1000
- • 0 ≤ k ≤ 10^6
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, multiply to the right until the product reaches k
Keep the longest window ending at right with product < k; add its length
Fix a start. Extend the end one step at a time, keeping a running product. Count every subarray while the product stays below k. Stop as soon as it reaches k, because the product can only grow from there.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.