Kth Smallest Product of Two Sorted Arrays - Problem

Given two sorted 0-indexed integer arrays nums1 and nums2 as well as an integer k, return the kth (1-based) smallest product of nums1[i] * nums2[j] where 0 <= i < nums1.length and 0 <= j < nums2.length.

The product of two integers can be positive, negative, or zero. You need to find the kth smallest product among all possible products.

Input & Output

Example 1 — Basic Case
$ Input: nums1 = [2,5], nums2 = [3,4,6], k = 3
Output: 12
💡 Note: All products: 2×3=6, 2×4=8, 2×6=12, 5×3=15, 5×4=20, 5×6=30. Sorted: [6,8,12,15,20,30]. The 3rd smallest is 12.
Example 2 — With Negative Numbers
$ Input: nums1 = [-4,-2,0,3], nums2 = [2,4], k = 6
Output: 0
💡 Note: Products: -4×2=-8, -4×4=-16, -2×2=-4, -2×4=-8, 0×2=0, 0×4=0, 3×2=6, 3×4=12. Sorted: [-16,-8,-8,-4,0,0,6,12]. The 6th smallest is 0.
Example 3 — Edge Case Small Arrays
$ Input: nums1 = [1,7], nums2 = [3], k = 2
Output: 21
💡 Note: Only two products: 1×3=3, 7×3=21. The 2nd smallest is 21.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 5 × 104
  • -105 ≤ nums1[i], nums2[j] ≤ 105
  • nums1 and nums2 are sorted in non-decreasing order
  • 1 ≤ k ≤ nums1.length × nums2.length

Visualization

Tap to expand
Kth Smallest Product of Two Sorted Arrays INPUT nums1 (sorted) 2 5 nums2 (sorted) 3 4 6 k = 3 (find 3rd smallest) All Products: 2*3=6 2*4=8 2*6=12 5*3=15 5*4=20 5*6=30 Sorted: 6,8,12,15,20,30 ALGORITHM STEPS 1 Binary Search Setup Search range: [min, max] lo=-10^10, hi=10^10 2 Count Products <= mid For each num in nums1, binary search in nums2 3 Adjust Search Range if count >= k: hi = mid else: lo = mid + 1 4 Return Answer When lo == hi, return lo as answer Complexity Time: O(n*log(n)*log(M)) Space: O(1) FINAL RESULT Binary Search Trace mid=12: count products <=12 2*3=6 OK 2*4=8 OK 2*6=12 OK 5*3=15 X (too big) count = 3 >= k=3 --> hi = 12 Output 12 3rd smallest = 12 (6 < 8 < 12 < 15 < 20 < 30) Key Insight: Instead of generating all n*m products (which could be 10^10), use binary search on the answer. For each candidate value, efficiently count how many products are <= that value using the sorted property of both arrays. Handle negative numbers by considering different cases separately. TutorialsPoint - Kth Smallest Product of Two Sorted Arrays | Optimal Solution
Asked in
Google 15 Amazon 8 Microsoft 12 Apple 5
23.4K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen