Median of Two Sorted Arrays — LeetCode 4 Python Solution
- Problem
- #4
- Pattern
- Monotonic Stack
- Reading time
- 3 min
- Source
- leetcode.com
The 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)).
Example
- Input
- nums1 = [1,3], nums2 = [2]
- Output
- 2.00000
- Explanation
- merged array = [1,2,3] and median is 2.
Python solution
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
def f(i: int, j: int, k: int) -> int:
if i >= m:
return nums2[j + k - 1]
if j >= n:
return nums1[i + k - 1]
if k == 1:
return min(nums1[i], nums2[j])
p = k // 2
x = nums1[i + p - 1] if i + p - 1 < m else inf
y = nums2[j + p - 1] if j + p - 1 < n else inf
return f(i + p, j, k - p) if x < y else f(i, j + p, k - p)
m, n = len(nums1), len(nums2)
a = f(0, 0, (m + n + 1) // 2)
b = f(0, 0, (m + n + 2) // 2)
return (a + b) / 2Complexity
| Measure | Complexity |
|---|---|
| Time | O(\log(m + n)) |
| Space | O(\log(m + n)) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 4. Median of Two Sorted Arrays is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
On study lists
This problem is on NeetCode 150 and Top Interview 150.
Frequently asked questions
- How hard is LeetCode 4. Median of Two Sorted Arrays?
- LeetCode 4. Median of Two Sorted Arrays is rated Hard on LeetCode.
- What is the time complexity of LeetCode 4. Median of Two Sorted Arrays?
- The Python solution on this page runs in O(\log(m + n)).
- What is the space complexity of LeetCode 4. Median of Two Sorted Arrays?
- The Python solution on this page uses O(\log(m + n)) auxiliary space.
- What topics does LeetCode 4. Median of Two Sorted Arrays cover?
- LeetCode 4. Median of Two Sorted Arrays is tagged Array, Binary Search and Divide and Conquer on LeetCode.