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)

๐Ÿ› ๏ธ 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

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit