#2040

Kth Smallest Product of Two Sorted Arrays

Hard
ArrayBinary SearchBinary SearchTwo Pointers
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log(max_product))
Space
O(n²)
O(1)
💡

Intuition

Time O(n log(max_product))Space O(1)

Instead of generating all products, we can use binary search to efficiently find the k-th smallest product. By determining how many products are less than or equal to a mid value, we can narrow down our search range.

⚙️

Algorithm

3 steps
  1. 1Step 1: Define the search range for products from min(nums1) * min(nums2) to max(nums1) * max(nums2).
  2. 2Step 2: Use binary search to find the k-th smallest product by checking how many products are less than or equal to a mid value.
  3. 3Step 3: Adjust the search range based on the count of products found.
solution.py21 lines
1# Full working Python code
2from bisect import bisect_right
3
4def count_less_equal(mid, nums1, nums2):
5    count = 0
6    for x in nums1:
7        count += bisect_right(nums2, mid // x)
8    return count
9
10def kthSmallestProduct(nums1, nums2, k):
11    left, right = min(nums1) * min(nums2), max(nums1) * max(nums2)
12    while left < right:
13        mid = (left + right) // 2
14        if count_less_equal(mid, nums1, nums2) < k:
15            left = mid + 1
16        else:
17            right = mid
18    return left
19
20result = kthSmallestProduct([2, 5], [3, 4], 2)
21print(result)

Complexity note: The time complexity is O(n log(max_product)) because we perform binary search on the product range, and for each mid value, we count the number of products in O(n) time. Space complexity is O(1) as we use only a few variables.

  • 1Understanding how to efficiently count products is crucial for optimizing the solution.
  • 2Binary search can significantly reduce the time complexity by narrowing down the search space.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.