
In Onsite interview, you may get asked hard coding question which require to have mathematics and algorithm knowledge. In this post we will discuss step by step approach to solve hard coding challenge.
Step By Step guide to find Median of Two Sorted Arrays
Question: Given two sorted arrays nums1
and nums2
of size m
and n
respectively, return the median of the two sorted arrays.
Example 1:
Input: nums1 = [1,3], nums2 = [2] Output: 2.00000 Explanation: merged array = [1,2,3] and median is 2.
Example 2:
Input: nums1 = [1,2], nums2 = [3,4] Output: 2.50000 Explanation: merged array = [1,2,3,4] and median is (2 + 3) / 2 = 2.5.
Example 3:
Input: nums1 = [0,0], nums2 = [0,0] Output: 0.00000
Example 4:
Input: nums1 = [], nums2 = [1] Output: 1.00000
Example 5:
Input: nums1 = [2], nums2 = [] Output: 2.00000
To Solve this problem we need to first create the function which will return median of the Array.
If we want to get Median of the array, we should calculate Given Array Length.
For now we are assuming array length is greater than 1. You can return false for corner cases like array length 0 or 1.
You can check if array length is even or odd number. For odd number you can easily find Median by returning array length divided by 2.
Read More: About Image Rotation Coding Challenge.
Median for Even Array Length
Median = array.length/2
Median for Odd Array Length
Median = (array.length/2 + array.length/2 - 1) / 2;
Checking Array Length is even or odd:
if array.length % 2 == 0, it is even otherwise it is odd.
Now, we know how to find Median of array, we need to find the way to merge two sorted array so we can check median.
Using Concat inbuilt method we can merge two arrays.
const array1 = [‘a’, ‘b’, ‘c’];
const array2 = [‘d’, ‘e’, ‘f’];
const array3 = array1.concat(array2);
Let’s put all code together to test it out.
const median = (arr1, arr2) => {
const arr3 = arr1.concat(arr2);
const midPoint = Math.floor(arr3.length / 2);
let medan;
if (arr3.length % 2 !== 0) {
medan = arr3[midPoint];
} else {
medan = (arr3[midPoint - 1] + arr3[midPoint]) / 2
}
return medan;
};