Median of Two Sorted Arrays
Explore how to compute the median of two sorted arrays with a time complexity of O(log(min(m, n))) and constant space. This lesson helps you understand and implement the optimal algorithm suitable for coding interviews involving sorted array merging and median finding.
We'll cover the following...
Statement
You’re given two sorted integer arrays, nums1 and nums2, of size and , respectively. Your task is to return the median of the two sorted arrays.
The overall run time complexity should be .
Constraints:
-
nums1.length -
nums2.length -
-
-
-
nums1[i],nums2[i]
Examples
Understand the problem
Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:
Median of Two Sorted Arrays
What is the output if the following arrays are given as input?
nums1 = [3, 5, 9, 10, 14]
nums2 = [1, 4, 6, 9, 30]
7.0
8.0
7.5
Figure it out!
We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.
Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.
Try it yourself
Implement your solution in the following coding playground.
We have left the solution to this challenge as an exercise for you. The optimal solution to this problem runs in O(log(min(m, n))) time and takes O(1) space. You may try to translate the logic of the solved puzzle into a coded solution.
double FindMedianSortedArrays(vector<int> nums1, vector<int>nums2){// Replace this placeholder return statement with your codereturn -1.0;}