NeetCode #245LC-713MediumSliding Window
← Back to All Problems#245 · #713 · Subarray Product Less Than K(乘积小于 K 的子数组)
📌 Problem Statement & Constraints
Given an array of integers
nums and an integer k, return the number of contiguous subarrays where the product of all elements is strictly less than k. Constraints: 1 <= nums.length <= 3 * 10^4, 1 <= nums[i] <= 1000, 0 <= k <= 10^6.💡 Core Algorithmic Approaches
- All values are positive, so the product of a window is monotone in its bounds -- a sliding window applies.
- Expand the right end, multiplying; while the product is at least
k, divide out the left element and advance. - After shrinking, the window
[l, r]is the longest valid window ending atr, so it contributesr - l + 1valid subarrays. - Note that
k <= 1makes the answer 0, since every element is at least 1.
💻 Benchmark Python3 Implementation
class Solution:
def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
if k <= 1:
return 0 # every product is at least 1
l = 0
prod = 1
res = 0
for r, x in enumerate(nums):
prod *= x
while prod >= k: # shrink until strictly less than k
prod //= nums[l]
l += 1
res += r - l + 1 # all starts in the window are valid
return res⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): each element enters and leaves the window at most once.
💾 Space Complexity
O(1): two scalars.
⚠️ Interview Pitfalls & Follow-ups
- Using
prod > kinstead ofprod >= k: the requirement is strictly less thank. - Forgetting the
k <= 1guard: withk = 1no subarray qualifies (all values are at least 1), and the shrink loop would divide by values repeatedly; the guard short-circuits it. - Dividing with
/instead of//: integer division is required to keep the product exact. - Assuming zeros in the array: the constraints guarantee
nums[i] >= 1, so the product never becomes zero and the window stays valid.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Sliding Window Problems
#219 · #219Contains Duplicate II#220 · #121Best Time to Buy and Sell Stock#221 · #2379Minimum Recolors to Get K Consecutive Black Blocks#222 · #1984Minimum Difference Between Highest and Lowest of K Scores#223 · #1343Number of Sub-arrays of Size K and Average Greater than or Equal to Threshold#224 · #1052Grumpy Bookstore Owner
中文速览与面试要点
乘积小于 K 的子数组
给你一个整数数组 nums 和一个整数 k,请你返回子数组内所有元素的乘积 严格小于 k 的连续子数组的数目。约束:1 ≤ nums.length ≤ 3 × 10^4;1 ≤ nums[i] ≤ 1000;0 ≤ k ≤ 10^6。
核心要点
- 滑动窗口 + 滚动乘积(标准解) :维护窗口内元素的乘积 prod 。右指针扩展;当 prod >= k 时收缩左边界(用整除移除)。
- 累加计数 :收缩结束后,以 r 结尾的合法子数组有 r − l + 1 个(左端点取 l..r)。
- 为什么可以整除移除 :窗口内元素都是正整数,且收缩是逐个移除,因此 prod //= nums[l] 恰好还原乘积。
- k ≤ 1 的边界 :此时任何非空子数组的乘积都 ≥ 1 ≥ k,答案必为 0,可直接返回。
常见陷阱
- 忘记 k <= 1 的特判 :当 k = 0 或 1 时, while prod >= k 会把窗口收缩到空,但 l 可能越过 r 导致逻辑混乱(实际仍能正确返回 0,但显式特判更安全)。
- 收缩条件写成 prod > k :题目要求 严格小于 k,因此应为 prod >= k 。
- 用除法而非整除 : prod /= nums[l] 会引入浮点误差,长期累积后判断可能出错。必须用 //= 。
- 累加写成 res += 1 :会严重少计。
- 用对数或双重循环 :前者有精度问题,后者是 O(n²)。
参考实现
class Solution:
def numSubarrayProductLessThanK(self, nums: list[int], k: int) -> int:
if k <= 1:
return 0 # 乘积至少为 1,不可能严格小于 k
l = 0
prod = 1
res = 0
for r, x in enumerate(nums):
prod *= x
while prod >= k: # 乘积过大 -> 收缩
prod //= nums[l]
l += 1
res += r - l + 1 # 以 r 结尾的合法子数组数
return res