Problem Description
Given two sorted integer arrays nums1 and nums2 and an integer k, find the kth (1-indexed) smallest product formed by nums1[i] * nums2[j] for all valid indices i and j.
Key Insights
- Both arrays are sorted but may contain negative, zero, and positive numbers.
- The product space is not sorted in a simple way due to sign changes. Therefore, a brute-force approach (forming all products) is infeasible given the constraint sizes.
- A binary search on the answer space (range of possible products) can be used. For a given candidate value, count the number of pairs whose product is less than or equal to that candidate.
- Counting pairs correctly requires handling three cases (negative, zero, and positive) separately since multiplication with negatives reverses inequalities.
Space and Time Complexity
Time Complexity: O((n1 + n2) * log(max_value)), where max_value is the search range (~10^10) and n1, n2 are the lengths of the arrays. Space Complexity: O(1)
Solution
The solution uses binary search over the potential product values. We set the low and high bounds based on the minimum and maximum possible products computed from the extremes of both arrays. For a given candidate mid, we count how many pairs (i, j) have a product <= mid. Since nums1 and nums2 are sorted, we can efficiently count this by iterating over one array and using binary search (or two pointer technique) on appropriate partitions of the other array. Special care is taken to handle negative numbers, zeros, and positives in order to correctly determine the count of valid pairs. Based on the count, we adjust our binary search until we narrow down the kth smallest product.