Median of Two Sorted Arrays
JavaScript
hard
40 mins
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)).
Examples
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 -10^6 <= nums1[i], nums2[i] <= 10^6
Function Signature
function findMedianSortedArrays(nums1, nums2) { // Your code here }
Test Cases
- Base cases: nums1 = [1], nums2 = [2] → 1.5, nums1 = [], nums2 = [1] → 1.0
- Simple cases: nums1 = [1,3], nums2 = [2] → 2.0, nums1 = [1,2], nums2 = [3,4] → 2.5
- Edge cases: nums1 = [], nums2 = [] → 0.0, nums1 = [1], nums2 = [] → 1.0
- Complex cases: nums1 = [1,2,3,4,5], nums2 = [6,7,8,9,10] → 5.5
- Mixed cases: nums1 = [1,3,5,7], nums2 = [2,4,6,8] → 4.5
Notes
- Both input arrays are sorted in ascending order
- Need to find the median without merging the arrays
- Median is the middle value (odd length) or average of two middle values (even length)
- Optimal solution uses binary search with O(log(min(m,n))) time complexity
- Handle edge cases where arrays might be empty or have different sizes
Companies:
Accenture
google
adobe
Solve Similar questions 🔥
Want to upskill? Explore our courses!
Namaste DSA
Master DSA from scratch with numerous problems, and expert guidance.
Namaste React
Wanna dive deep into React and become Frontend Expert? Learn with me now!
Namaste Frontend System Design
The most comprehensive and detailed course for frontend system design.
Namaste Node.js
Wanna dive deep into Node.js? Enroll into `Namaste Node.js` now!
