Find Median of Two Sorted Arrays — LeetCode hard

iAwale
2 min readMar 9, 2020

One of the simplest ways to solve this is to merge both arrays, then calculate the median with respect to the total length of the array. The median will be in the middle if odd number of items, else it will be around the middle since we need to get the average of the two middle terms. Since both of the arrays are sorted in this instance, it makes the process a lot easier.

The arrays given to us are like the last step of the MergeSort. To make it even better knowing that the median is going to be somewhere in the middle of the final merged array, we only need about half of the two arrays sorted. Thus we have the size:

int size = ((la+lb)/2)+1; 
# +1 to include both cases of even and odd number of items

If there are even number of items then we need the to divide the last two items in our semi-merged array, while we return only the last item on our new semi-merged array to get the median.

class Solution {
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
int la = nums1.length;
int lb = nums2.length;
int size = ((la+lb)/2)+1;
int [] mar = new int [size];
int i = 0, j = 0, count = 0;
while(i < la && j < lb && count < size) {
if(nums1[i] < nums2[j]) {
mar[count++] = nums1[i++];
} else {
mar[count++] = nums2[j++];
}
}
if (i<la ){
while (i < la && count < size){
mar[count++]= nums1[i++];
}
}else {
while (j < lb && count < size){
mar[count++]= nums2[j++];
}
}
if((la+lb)%2 == 0){
return (mar[size-1] + mar[size-2])/2.0;
} else {
return mar[size-1];
}
}
}

Credits to : https://leetcode.com/problems/median-of-two-sorted-arrays/

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

iAwale
iAwale

Written by iAwale

Learn Productivity. Learn Growth. Learn Coding. Learn to Build Applications. If you like the content please follow Twitter Youtube

No responses yet

Write a response