⚡Flashcard Drill➔
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

  1. All values are positive, so the product of a window is monotone in its bounds -- a sliding window applies.
  2. Expand the right end, multiplying; while the product is at least k, divide out the left element and advance.
  3. After shrinking, the window [l, r] is the longest valid window ending at r, so it contributes r - l + 1 valid subarrays.
  4. Note that k <= 1 makes 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 > k instead of prod >= k: the requirement is strictly less than k.
  • Forgetting the k <= 1 guard: with k = 1 no 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.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

乘积小于 K 的子数组

给你一个整数数组 nums 和一个整数 k,请你返回子数组内所有元素的乘积 严格小于 k 的连续子数组的数目。约束:1 ≤ nums.length ≤ 3 × 10^4;1 ≤ nums[i] ≤ 1000;0 ≤ k ≤ 10^6。

核心要点

  • 滑动窗口 + 滚动乘积(标准解) :维护窗口内元素的乘积 prod 。右指针扩展;当 prod &gt;= k 时收缩左边界(用整除移除)。
  • 累加计数 :收缩结束后,以 r 结尾的合法子数组有 r − l + 1 个(左端点取 l..r)。
  • 为什么可以整除移除 :窗口内元素都是正整数,且收缩是逐个移除,因此 prod //= nums[l] 恰好还原乘积。
  • k ≤ 1 的边界 :此时任何非空子数组的乘积都 ≥ 1 ≥ k,答案必为 0,可直接返回。

常见陷阱

  • 忘记 k &lt;= 1 的特判 :当 k = 0 或 1 时, while prod &gt;= k 会把窗口收缩到空,但 l 可能越过 r 导致逻辑混乱(实际仍能正确返回 0,但显式特判更安全)。
  • 收缩条件写成 prod &gt; k :题目要求 严格小于 k,因此应为 prod &gt;= 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