From a3779de10d459b01ba81c10a9796098e9b3aa76c Mon Sep 17 00:00:00 2001 From: chayan das Date: Wed, 25 Jun 2025 14:59:17 +0530 Subject: [PATCH] Create 2040. Kth Smallest Product of Two Sorted Arrays --- ... Kth Smallest Product of Two Sorted Arrays | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 2040. Kth Smallest Product of Two Sorted Arrays diff --git a/2040. Kth Smallest Product of Two Sorted Arrays b/2040. Kth Smallest Product of Two Sorted Arrays new file mode 100644 index 0000000..38ceea0 --- /dev/null +++ b/2040. Kth Smallest Product of Two Sorted Arrays @@ -0,0 +1,45 @@ +class Solution { +public: + long long kthSmallestProduct(vector& nums1, vector& nums2, long long k) { + long long left = -1e10, right = 1e10; + while (left < right) { + long long mid = left + (right - left) / 2; + if (countProducts(nums1, nums2, mid) < k) + left = mid + 1; + else + right = mid; + } + return left; + } + + long long countProducts(vector& nums1, vector& nums2, long long target) { + long long count = 0; + for (int num1 : nums1) { + if (num1 == 0) { + if (target >= 0) count += nums2.size(); + continue; + } + int low = 0, high = nums2.size(); + if (num1 > 0) { + while (low < high) { + int mid = low + (high - low) / 2; + if (1LL * num1 * nums2[mid] <= target) + low = mid + 1; + else + high = mid; + } + count += low; + } else { + while (low < high) { + int mid = low + (high - low) / 2; + if (1LL * num1 * nums2[mid] <= target) + high = mid; + else + low = mid + 1; + } + count += nums2.size() - low; + } + } + return count; + } +};