⌘K
Flycodx

Median of Two Sorted Arrays

Median of Two Sorted Arrays

HardBinary Search100% accepted

Given two sorted arrays nums1 and nums2 of sizes m and n, return the median of the two sorted arrays. The overall run time complexity must be O(log(m+n)). If the combined length is odd, the median is the middle element. If even, the median is the average of the two middle elements — print as a decimal. Example: nums1=[1 3], nums2=[2] → combined sorted=[1 2 3], median=2

Input format — only if your code reads from stdin

Input format: - First line: integer m (size of first array) - Second line: m space-separated sorted integers - Third line: integer n (size of second array) - Fourth line: n space-separated sorted integers Output: the median as a number (integer or decimal with one decimal place).

Approach

Binary search on the smaller array to find a partition where all elements on the left of partition1 and partition2 are ≤ all elements on the right. Then median = max(left halves) if odd total, or avg(max left, min right) if even total.

Input

2 1 3 1 2

Output

2
  • •0 ≤ m, n ≤ 1000, -10^6 ≤ elements ≤ 10^6, m + n ≥ 1
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3