2040. Kth Smallest Product of Two Sorted Arrays #1850
-
Topics: Given two sorted 0-indexed integer arrays Example 1:
Example 2:
Example 3:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the k-th smallest product of pairs from two sorted arrays. The challenge lies in efficiently handling both negative and non-negative numbers while leveraging the sorted nature of the arrays to avoid a brute-force approach. Approach
Let's implement this solution in PHP: 2040. Kth Smallest Product of Two Sorted Arrays <?php
/**
* @param Integer[] $nums1
* @param Integer[] $nums2
* @param Integer $k
* @return Integer
*/
function kthSmallestProduct($nums1, $nums2, $k) {
$A1 = []; $A2 = [];
$B1 = []; $B2 = [];
separate($nums1, $A1, $A2);
separate($nums2, $B1, $B2);
$negCount = count($A1) * count($B2) + count($A2) * count($B1);
$sign = 1;
if ($k > $negCount) {
$k -= $negCount;
} else {
$k = $negCount - $k + 1;
$sign = -1;
list($B1, $B2) = [$B2, $B1];
}
$left = 0;
$right = 10000000000;
while ($left < $right) {
$mid = intval(($left + $right) / 2);
$count1 = numProductNoGreaterThan($A1, $B1, $mid);
$count2 = numProductNoGreaterThan($A2, $B2, $mid);
$total = $count1 + $count2;
if ($total >= $k) {
$right = $mid;
} else {
$left = $mid + 1;
}
}
return $sign * $left;
}
/**
* @param $arr
* @param $neg
* @param $nonNeg
* @return void
*/
function separate($arr, &$neg, &$nonNeg) {
foreach ($arr as $num) {
if ($num < 0) {
$neg[] = -$num;
} else {
$nonNeg[] = $num;
}
}
$neg = array_reverse($neg);
}
/**
* @param $A
* @param $B
* @param $m
* @return int
*/
function numProductNoGreaterThan($A, $B, $m) {
if (empty($A) || empty($B)) {
return 0;
}
$count = 0;
$j = count($B) - 1;
foreach ($A as $a) {
while ($j >= 0 && $a * $B[$j] > $m) {
$j--;
}
$count += $j + 1;
}
return $count;
}
// Test cases
echo kthSmallestProduct([2, 5], [3, 4], 2) . "\n"; // Output: 8
echo kthSmallestProduct([-4, -2, 0, 3], [2, 4], 6) . "\n"; // Output: 0
echo kthSmallestProduct([-2, -1, 0, 1, 2], [-3, -1, 2, 4, 5], 3) . "\n"; // Output: -6
?> Explanation:
This approach efficiently narrows down the search space using binary search and leverages the sorted nature of arrays to count valid products in linear time, making it suitable for large input sizes. |
Beta Was this translation helpful? Give feedback.
We need to find the k-th smallest product of pairs from two sorted arrays. The challenge lies in efficiently handling both negative and non-negative numbers while leveraging the sorted nature of the arrays to avoid a brute-force approach.
Approach
Separate Arrays by Sign:
Count Negative Products:
Determine Sign and Adjust k:
k
e…