Open In App

Median of Two Sorted Arrays of Different Sizes using JavaScript

Last Updated : 16 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two arrays, our goal is to find the median of two sorted arrays of different sizes by merging both of them. The median is the middle value of the array after dividing it into two halves.

Example:

Input:  Arr1: [1,4,5], Arr2: [2,8,7,3]
Output: Median = 4
Explanation: The merged and sorted array is: ar3[] = [1,2,3,4,5,7,8]
The median is 4

In this approach, we will be performing binary search on the shorter array so that we can partition it in such a way that the newly combined left half of both the arrays will have elements less than the combined right half. Adjust the partition point until the condition for median gets satisfied. If the combined length of the new array is odd, return the maximum element of the left partition. If it's even, return the average of the maximum element of the left partition and the minimum element of the right partition.

Example: The below example shows how to find Median of two sorted arrays of different sizes using Binary Search on the Smaller Array.


Output
2

Time Complexity: O(log(min(m, n))), where m and n are the lengths of the two input arrays.

Space Complexity: O(1)

Using Two-Pointers Approach

The function find_Median_fun finds the median of two sorted arrays by iterating through them simultaneously with two pointers, selecting elements in ascending order until reaching the middle point of the combined arrays. It determines the median based on whether the total length is even or odd and returns the result accordingly.

Example: The example below shows how to find Median of two sorted arrays of different sizes using JavaScript Using Two-Pointers.


Output
Median: 2

Time Complexity: O(m + n), where m and n are the lengths of the two input arrays.

Space Complexity: O(1)


Next Article

Similar Reads