Median of 2 Sorted Arrays of Different Sizes

gfg, potd, java, python, hard, appris, edge_case, note

Problem Statement #

Given two sorted arrays array1 and array2 of size m and n respectively. Find the median of the two sorted arrays.

Appris #

Note #

Edge Case #

4
1 2 3 4
6
5 6 7 8 9 10
1
4
1
2

Solution #

Java #


class GFG 
{ 
    static double medianOfArrays(int n, int m, int a[], int b[]) 
    {
        // Your Code Here
        int mid = ((n+m)/2)+1;
        int[] arr = new int[mid];
        
        int i=0,j=0,k=0;
        
        while(k<mid && i<n && j<m ){
            if(a[i]<=b[j]){
                arr[k++]=a[i++];
            }else{
                arr[k++]=b[j++];
            }
        }
        
        while(k<mid && i<n){
            arr[k++]=a[i++];
        }
        
        while(k<mid && j<m){
            arr[k++]=b[j++];
        }
        
        if((n+m)%2==1){
            return arr[mid-1];
        }else{
            return (arr[mid-1] + arr[mid-2])/2.0;
        }

    }
}

Python #

class Solution:
    def MedianOfArrays(self, array1, array2):
        #code here
        """
        Naive approach
        """
        a = array1+array2
        a.sort();
        
        n = len(a);
        if(n%2==0):
            val = (a[n//2]+a[n//2-1])/2
            if int(val)!=val:
                return val
            else:
                return int(val);
        else:
            return a[n//2];