Kth Smallest Product of Two Sorted Arrays Problem
Description
LeetCode Problem 2040.
Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the k^th (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.
Example 1:
Input: nums1 = [2,5], nums2 = [3,4], k = 2
Output: 8
Explanation: The 2 smallest products are:
- nums1[0] * nums2[0] = 2 * 3 = 6
- nums1[0] * nums2[1] = 2 * 4 = 8
The 2^nd smallest product is 8.
Example 2:
Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6
Output: 0
Explanation: The 6 smallest products are:
- nums1[0] * nums2[1] = (-4) * 4 = -16
- nums1[0] * nums2[0] = (-4) * 2 = -8
- nums1[1] * nums2[1] = (-2) * 4 = -8
- nums1[1] * nums2[0] = (-2) * 2 = -4
- nums1[2] * nums2[0] = 0 * 2 = 0
- nums1[2] * nums2[1] = 0 * 4 = 0
The 6^th smallest product is 0.
Example 3:
Input: nums1 = [-2,-1,0,1,2], nums2 = [-3,-1,2,4,5], k = 3
Output: -6
Explanation: The 3 smallest products are:
- nums1[0] * nums2[4] = (-2) * 5 = -10
- nums1[0] * nums2[3] = (-2) * 4 = -8
- nums1[4] * nums2[0] = 2 * (-3) = -6
The 3^rd smallest product is -6.
Constraints:
1 <= nums1.length, nums2.length <= 5 * 10^4-10^5 <= nums1[i], nums2[j] <= 10^51 <= k <= nums1.length * nums2.lengthnums1andnums2are sorted.
Solution
Approach: Binary search on the answer
Binary search the value p of the k-th smallest product in the range [-M, M], where M is the largest absolute value in nums1 times the largest in nums2. For each p, count the products that are at most p. If the count is at least k, the answer is at most p, otherwise it is larger.
To count the products at most p, take each x in nums1 and binary search in nums2:
- if
x > 0, the productsx * nums2[i]grow withi, so the count is the number ofiwithx * nums2[i] <= p; - if
x < 0, the products shrink asigrows, so the count is the number ofiwithx * nums2[i] <= pat the end of the array; - if
x = 0, every product is0, so the count is the whole ofnums2whenp >= 0and nothing otherwise.
The time complexity is O(m log n log M) and the space complexity is O(1), where m and n are the lengths of nums1 and nums2.
from bisect import bisect_left, bisect_right
class Solution:
def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int:
n = len(nums2)
def count(p: int) -> int:
cnt = 0
for x in nums1:
if x > 0:
cnt += bisect_right(nums2, p // x)
elif x < 0:
cnt += n - bisect_left(nums2, -((-p) // x))
elif p >= 0:
cnt += n
return cnt
mx = max(abs(nums1[0]), abs(nums1[-1])) * max(abs(nums2[0]), abs(nums2[-1]))
l, r = -mx, mx
while l < r:
mid = (l + r) >> 1
if count(mid) >= k:
r = mid
else:
l = mid + 1
return l