⚡Flashcard Drill➔
NeetCode #301LC-2040HardBinary Search
← Back to All Problems

#301 · #2040 · Kth Smallest Product of Two Sorted Arrays(两个有序数组的第 K 小乘积)

📌 Problem Statement & Constraints

Given two sorted arrays nums1 and nums2 and an integer k, return the k-th smallest product among all nums1[i] * nums2[j]. Constraints: 1 <= nums1.length, nums2.length <= 5 * 10^4, -10^5 <= nums1[i], nums2[j] <= 10^5, 1 <= k <= nums1.length * nums2.length.

💡 Core Algorithmic Approaches

  1. Binary search on the product value x: "how many pairs have product at most x" is monotone in x.
  2. For each element a of nums1, the valid partners in the sorted nums2 form a prefix or a suffix depending on the sign of a.
  3. For a > 0, count b <= x / a via bisect_right; for a < 0, count b >= ceil(x / a) via bisect_left; for a == 0, all pairs count when x >= 0.
  4. The sign handling is the crux: dividing by a negative number flips the inequality.

💻 Benchmark Python3 Implementation

class Solution:
    def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:
        from bisect import bisect_left, bisect_right
        n2 = len(nums2)

        def count(x: int) -> int:
            """number of pairs with product <= x"""
            cnt = 0
            for a in nums1:
                if a > 0:
                    cnt += bisect_right(nums2, x // a)      # b <= floor(x / a)
                elif a < 0:
                    # a * b <= x  <=>  b >= ceil(x / a)  (dividing flips the sign)
                    need = -((-x) // a)                     # ceil(x / a)
                    cnt += n2 - bisect_left(nums2, need)
                else:
                    if x >= 0:
                        cnt += n2                           # 0 <= x
            return cnt

        # candidate product range from the four extreme corners
        cands = [nums1[0] * nums2[0], nums1[0] * nums2[-1],
                 nums1[-1] * nums2[0], nums1[-1] * nums2[-1]]
        lo, hi = min(cands), max(cands)
        while lo < hi:
            mid = (lo + hi) // 2
            if count(mid) >= k:
                hi = mid
            else:
                lo = mid + 1
        return lo

⚡ Complexity Deep Dive

⏱️ Time Complexity
O((n + m) log(range)): each counting pass is O(n log m) via binary search.
💾 Space Complexity
O(1): a few scalars.

⚠️ Interview Pitfalls & Follow-ups

  • Ignoring the sign of a: for negative a the inequality flips, so the valid partners form a suffix rather than a prefix.
  • Using x // a for negative a: Python's floor division rounds toward negative infinity, so the ceiling must be computed as -((-x) // a).
  • Forgetting the a == 0 case: the product is 0, which is at most x exactly when x >= 0.
  • Setting the search range to [min product, max product] incorrectly: the extremes are always achieved at the corners of the two arrays, hence the four candidates.
  • Enumerating all products: up to 2.5 * 10^9 pairs.
⚡
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 Binary Search Problems

中文速览与面试要点

两个有序数组的第 K 小乘积

给你两个 从小到大排好序 且下标从 0 开始的整数数组 nums1 和 nums2,以及一个整数 k。定义一对值 (u, v) ,其中第一个元素来自 nums1,第二个元素来自 nums2。请找到和最小的 k 个数对 (u1, v1), (u2, v2), ... 中 乘积 第 k 小的值。约束:1 ≤ nums1.length, nums2.length ≤ 5 × 10^4;-10^5 ≤ nums1[i], nums2[i] ≤ 10^5;1 ≤ k ≤ nums1.length × nums2.length。

核心要点

  • 二分乘积值 + 逐元素计数(标准解) :二分「乘积值 x」,判定「乘积 ≤ x 的数对个数是否 ≥ k」。
  • 计数的分类讨论(核心难点) :对 nums1 中的每个 a 分三种情况:
  • a &gt; 0 :需 a × b &lt;= x ,即 b &lt;= floor(x / a) ,个数为 bisect_right(nums2, x // a) 。
  • a &lt; 0 :需 a × b &lt;= x ,除以负数变号,即 b &gt;= ceil(x / a) ,个数为 len(nums2) − bisect_left(nums2, ceil(x/a)) 。
  • a == 0 : a × b = 0 &lt;= x 当且仅当 x &gt;= 0 ,此时全部 n2 个都满足。
  • 整数 ceil 的精确写法 : ceil(x / a) 在 a &lt; 0 时等于 -((-x) // a) ,避免浮点误差。

常见陷阱

  • 对 a &lt; 0 的情况忘记变号 :除以负数会翻转不等号方向,必须写成 b &gt;= ceil(x/a) 。这是本题最容易出错的地方。
  • 用浮点 math.ceil(x / a) :x 与 a 可达 ±10^5 量级,乘积可达 10^10,浮点除法在边界上可能出错。必须用整数写法 -((-x) // a) 。
  • a == 0 时忘记处理 :0 乘以任何数都是 0,因此只要 x &gt;= 0 就全部满足。漏掉这一分支会导致计数偏少。
  • 二分范围写成 [−10^10, 10^10] :虽然正确但二分次数多;用四个角点乘积的极值更紧。
  • 误读题意 :题目求的是 乘积 第 k 小,不是「数对和」第 k 小(那是 373 题)。

参考实现

from bisect import bisect_left, bisect_right

class Solution:
    def kthSmallestProduct(self, nums1: list[int], nums2: list[int], k: int) -> int:
        n2 = len(nums2)

        def count_le(x: int) -> int:
            """乘积 <= x 的数对个数。"""
            cnt = 0
            for a in nums1:
                if a > 0:
                    # a*b <= x -> b <= floor(x/a)
                    cnt += bisect_right(nums2, x // a)
                elif a < 0:
                    # a*b <= x -> b >= ceil(x/a)(除以负数变号)
                    lo = -((-x) // a)           # ceil(x/a) 的精确整数写法
                    cnt += n2 - bisect_left(nums2, lo)
                else:
                    if x >= 0:                  # 0 * b = 0 <= x
                        cnt += n2
            return cnt

        # 二分范围:四个角点乘积的极值
        corners = [nums1[0] * nums2[0], nums1[0] * nums2[-1],
                   nums1[-1] * nums2[0], nums1[-1] * nums2[-1]]
        l, r = min(corners), max(corners)

        while l < r:
            mid = (l + r) // 2
            if count_le(mid) >= k:
                r = mid
            else:
                l = mid + 1
        return l