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
- Binary search on the product value
x: "how many pairs have product at mostx" is monotone inx. - For each element
aofnums1, the valid partners in the sortednums2form a prefix or a suffix depending on the sign ofa. - For
a > 0, countb <= x / aviabisect_right; fora < 0, countb >= ceil(x / a)viabisect_left; fora == 0, all pairs count whenx >= 0. - 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 negativeathe inequality flips, so the valid partners form a suffix rather than a prefix. - Using
x // afor negativea: Python's floor division rounds toward negative infinity, so the ceiling must be computed as-((-x) // a). - Forgetting the
a == 0case: the product is 0, which is at mostxexactly whenx >= 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.
🧩 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 > 0 :需 a × b <= x ,即 b <= floor(x / a) ,个数为 bisect_right(nums2, x // a) 。
- a < 0 :需 a × b <= x ,除以负数变号,即 b >= ceil(x / a) ,个数为 len(nums2) − bisect_left(nums2, ceil(x/a)) 。
- a == 0 : a × b = 0 <= x 当且仅当 x >= 0 ,此时全部 n2 个都满足。
- 整数 ceil 的精确写法 : ceil(x / a) 在 a < 0 时等于 -((-x) // a) ,避免浮点误差。
常见陷阱
- 对 a < 0 的情况忘记变号 :除以负数会翻转不等号方向,必须写成 b >= ceil(x/a) 。这是本题最容易出错的地方。
- 用浮点 math.ceil(x / a) :x 与 a 可达 ±10^5 量级,乘积可达 10^10,浮点除法在边界上可能出错。必须用整数写法 -((-x) // a) 。
- a == 0 时忘记处理 :0 乘以任何数都是 0,因此只要 x >= 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