HARD NC#34 Binary Search
4. Median of Two Sorted Arrays
๐ Problem
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)).
๐ง Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- โขArray methods (`push`, `pop`, `shift`, `slice`)
- โขObject/Map/Set usage patterns
- โขFunction parameter and return typing
- โขIn-place array updates
- โขSorted array traversal
- โขBoundary condition checks
Logical Thinking Concepts
- โขDefine invariants before coding
- โขCheck edge cases first (`[]`, single element, duplicates)
- โขEstimate time/space before implementation
- โขApply Two Pointers reasoning pattern
- โขApply Binary Search reasoning pattern
๐ก Approach
- โ Use binary search to partition both arrays into left and right halves
- โ Ensure all elements in left half are less than or equal to elements in right half
- โ If total length is odd, median is min of right halves; if even, average of max left and min right
- โ Always binary search on the smaller array for efficiency
- โ Time: O(log(min(m,n))), Space: O(1)
๐งญ Prerequisites
๐ ๏ธ Hints & Pitfalls
Hints
- โขUse binary search to partition both arrays into left and right halves
- โขEnsure all elements in left half are less than or equal to elements in right half
- โขIf total length is odd, median is min of right halves; if even, average of max left and min right
Common Pitfalls
- โขAlways binary search on the smaller array for efficiency
- โขTime: O(log(min(m,n))), Space: O(1)
๐งช Test Cases
Hidden tests on submit: 4
Test Case 1
Not run Input:
findMedianSortedArrays([1,3], [2]); Expected:
2 Test Case 2
Not run Input:
findMedianSortedArrays([1,2], [3,4]); Expected:
2.5 Test Case 3
Not run Input:
findMedianSortedArrays([0,0], [0,0]); Expected:
0 ๐ Code Editor
๐ค Output