Search⌘ K
AI Features

Median of Two Sorted Arrays

Explore how to compute the median of two sorted integer arrays with an optimal algorithm that runs in logarithmic time. This lesson helps you understand the problem constraints and develop a solution focused on both time and space efficiency.

Statement

You’re given two sorted integer arrays, nums1 and nums2, of size mm and nn, respectively. Your task is to return the median of the two sorted arrays.

The overall run time complexity should be O(log(m,n))O(\log (m, n)).

Constraints:

  • nums1.length ==== mm

  • nums2.length ==== nn

  • 0m10000 \leq m \leq 1000

  • 0n10000 \leq n \leq 1000

  • 1m+n20001 \leq m + n \leq 2000

  • 105-10^5 \leq nums1[i], nums2[i] 105\leq 10^5

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

1.

What is the output if the following arrays are given as input?

nums1 = [3, 5, 9, 10, 14]

nums2 = [1, 4, 6, 9, 30]

A.

7.0

B.

8.0

C.

7.5


1 / 2

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.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

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.

Python
usercode > main.py
def find_median_sorted_arrays(nums1, nums2):
# Replace this placeholder return statement with your code
return 1.0
Median of Two Sorted Arrays