2025-06-25 Daily Challenge
Today I have done leetcode's June LeetCoding Challenge with cpp
.
June LeetCoding Challenge 25
Description
Kth Smallest Product of Two Sorted Arrays
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
.
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 2nd 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 6th 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 3rd smallest product is -6.
Constraints:
1 <= nums1.length, nums2.length <= 5 * 104
-105 <= nums1[i], nums2[j] <= 105
1 <= k <= nums1.length * nums2.length
nums1
andnums2
are sorted.
Solution
class Solution {
long long countLE(const vector<int>& nums1, const vector<int>& nums2, long long target) {
long long result = 0;
int len2 = nums2.size();
for(auto n1 : nums1) {
if(!n1) {
if(target >= 0) result += len2;
continue;
}
int low = 0;
int high = len2 - 1;
while(low <= high) {
int mid = (low + high) / 2;
if((n1 > 0 && 1LL * n1 * nums2[mid] <= target) ||
(n1 < 0 && 1LL * n1 * nums2[mid] > target)) {
low = mid + 1;
} else {
high = mid - 1;
}
}
result += n1 < 0 ? len2 - low : low;
}
return result;
}
public:
long long kthSmallestProduct(vector<int>& nums1, vector<int>& nums2, long long k) {
long long mmin = min({1LL * nums1.front() * nums2.back(), 1LL * nums1.back() * nums2.front(), 1LL * nums1.front() * nums2.front(), 1LL * nums2.back() * nums2.back()});
long long mmax = max({1LL * nums1.front() * nums2.back(), 1LL * nums1.back() * nums2.front(), 1LL * nums1.front() * nums2.front(), 1LL * nums2.back() * nums2.back()});
// cout << "~~~~~~~~~~~~~~~~~~~~~" << endl;
while(mmin < mmax) {
long long mmid = (mmin + mmax - (mmax <= 0)) / 2;
// cout << mmin << ' ' << mmax << ' ' << mmid << ' ' << countLE(nums1, nums2, mmid) << endl;
if(countLE(nums1, nums2, mmid) < k) {
mmin = mmid + 1;
} else {
mmax = mmid;
}
}
return mmin;
}
};
// Accepted
// 112/112 cases passed (541 ms)
// Your runtime beats 71.3 % of cpp submissions
// Your memory usage beats 41.69 % of cpp submissions (98.1 MB)