Solving Leetcode Interviews in Seconds with AI: Kth Smallest Product of Two Sorted Arrays
Introduction
In this blog post, we will explore how to solve the LeetCode problem "2040" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
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 and nums2 are sorted.
Explanation
Here's the solution:
- Binary Search for the Kth Smallest Product: The core idea is to use binary search on the range of possible product values to find the kth smallest product. We determine a
midvalue in the range and efficiently count how many products are less than or equal tomid. Efficient Counting of Products <= mid: For each number in
nums1, we use binary search innums2to find how many numbers innums2when multiplied by the current number innums1result in a product less than or equal tomid. Care is taken to handle negative, zero, and positive numbers correctly.Time Complexity: O(m log(m*n) log(range)), where
mandnare the lengths ofnums1andnums2and range is the range of possible products. Space Complexity: O(1)
Code
def kthSmallestProduct(nums1, nums2, k):
def count_less_equal(mid):
count = 0
for num1 in nums1:
low = 0
high = len(nums2) - 1
idx = -1
while low <= high:
m = (low + high) // 2
if num1 * nums2[m] <= mid:
idx = m
low = m + 1
else:
high = m - 1
if idx != -1:
count += (idx + 1)
return count
low = -10**10
high = 10**10
ans = 0
while low <= high:
mid = (low + high) // 2
if count_less_equal(mid) >= k:
ans = mid
high = mid - 1
else:
low = mid + 1
return ans