Solving Leetcode Interviews in Seconds with AI: Median of Two Sorted Arrays
Introduction
In this blog post, we will explore how to solve the LeetCode problem "4" 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 arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2. Example 2: Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5. Constraints: nums1.length == m nums2.length == n 0 <= m <= 1000 0 <= n <= 1000 1 <= m + n <= 2000 -106 <= nums1[i], nums2[i] <= 106
Explanation
Here's a solution to find the median of two sorted arrays with O(log(m+n)) time complexity:
- Binary Search: The core idea is to perform binary search on the smaller array. This allows us to efficiently find the correct partition points in both arrays that would result in a merged sorted array.
- Partitioning: We aim to find partition points
iinnums1andjinnums2such that all elements to the left of the partitions are smaller than all elements to the right. This ensures we are effectively splitting the merged array into two halves with equal (or nearly equal) lengths. Median Calculation: Once the correct partitions are found, the median can be easily calculated based on the values around the partition points, considering whether the total number of elements is even or odd.
Time Complexity: O(log(min(m, n))) Space Complexity: O(1)
Code
def findMedianSortedArrays(nums1, nums2):
"""
Finds the median of two sorted arrays.
Args:
nums1: The first sorted array.
nums2: The second sorted array.
Returns:
The median of the two sorted arrays.
"""
if len(nums1) > len(nums2):
nums1, nums2 = nums2, nums1 # Ensure nums1 is the smaller array
m, n = len(nums1), len(nums2)
low, high = 0, m
while low <= high:
partitionX = (low + high) // 2
partitionY = (m + n + 1) // 2 - partitionX
maxLeftX = nums1[partitionX - 1] if partitionX > 0 else float('-inf')
minRightX = nums1[partitionX] if partitionX < m else float('inf')
maxLeftY = nums2[partitionY - 1] if partitionY > 0 else float('-inf')
minRightY = nums2[partitionY] if partitionY < n else float('inf')
if maxLeftX <= minRightY and maxLeftY <= minRightX:
if (m + n) % 2 == 0:
return (max(maxLeftX, maxLeftY) + min(minRightX, minRightY)) / 2.0
else:
return max(maxLeftX, maxLeftY)
elif maxLeftX > minRightY:
high = partitionX - 1
else:
low = partitionX + 1