Median of 2 sorted arrays

Binary Search FAQs Hard

Given two sorted arrays arr1 and arr2 of size m and n respectively, return the median of the two sorted arrays.


The median is defined as the middle value of a sorted list of numbers. In case the length of the list is even, the median is the average of the two middle elements.

Examples:

Input: arr1 = [2, 4, 6], arr2 = [1, 3, 5]

Output: 3.5

Explanation: The array after merging arr1 and arr2 will be [ 1, 2, 3, 4, 5, 6 ]. As the length of the merged list is even, the median is the average of the two middle elements. Here two medians are 3 and 4. So the median will be the average of 3 and 4, which is 3.5.

Input: arr1 = [2, 4, 6], arr2 = [1, 3]

Output: 3.0

Explanation: The array after merging arr1 and arr2 will be [ 1, 2, 3, 4, 6 ]. The median is simply 3.

Input: arr1 = [2, 4, 5], arr2 = [1, 6]

Constraints

  • 0 <= m <= 1000
  • 0 <= n <= 1000
  • -106 <= arr1[i], arr2[i] <= 106

Hints

  • Instead of merging the arrays fully, focus only on locating the required middle element(s).
  • Divide both arrays into two halves such that the left halves contain the smaller elements and the right halves contain the larger elements.

Company Tags

Square Visa Target American Express Lyft Bungie Micron Technology Roche Ubisoft Alibaba Snowflake Ernst & Young Riot Games Reddit IBM Splunk Pinterest Etsy Unity Technologies Salesforce KPMG Western Digital Stripe Zomato Walmart Google Microsoft Amazon Meta Apple Netflix Adobe