Skip to main content

Median of Two Sorted Arrays

 

Problem Understanding:

In simpler terms, you need to find the middle value of the combined, sorted array formed by merging nums1 and nums2. If the combined array has an even number of elements, you should return the average of the two middle values. If it has an odd number of elements, you should return the middle value itself.

Approach 1: Merge and Sort

  • Create a new array with a size equal to the total number of elements in both input arrays.
  • Insert elements from both input arrays into the new array.
  • Sort the new array.
  • Find and return the median of the sorted array.

Time Complexity

  • In the worst case TC is O((n + m) * log(n + m)).

Space Complexity

  • O(n + m), where ‘n’ and ‘m’ are the sizes of the arrays.

Approach 2: Two-Pointer Method

  • Initialize two pointers, i and j, both initially set to 0.
  • Move the pointer that corresponds to the smaller value forward at each step.
  • Continue moving the pointers until you have processed half of the total number of elements.
  • Calculate and return the median based on the values pointed to by i and j.

Time Complexity

  • O(n + m), where ‘n’ & ‘m’ are the sizes of the two arrays.

Space Complexity

  • O(1).

Approach 3: Binary Search

  • Use binary search to partition the smaller of the two input arrays into two parts.
  • Find the partition of the larger array such that the sum of elements on the left side of the partition in both arrays is half of the total elements.
  • Check if this partition is valid by verifying if the largest number on the left side is smaller than the smallest number on the right side.
  • If the partition is valid, calculate and return the median.

Time Complexity

  • O(logm/logn)

Space Complexity

  • O(1)

SMALL REQUEST : If you found this post even remotely helpful, be kind enough to smash a upvote. I will be grateful.I will be motivated😊😊


Code Brute Force- Merge and Sort

import java.util.Arrays;

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        // Get the sizes of both input arrays.
        int n = nums1.length;
        int m = nums2.length;

        // Merge the arrays into a single sorted array.
        int[] merged = new int[n + m];
        int k = 0;
        for (int i = 0; i < n; i++) {
            merged[k++] = nums1[i];
        }
        for (int i = 0; i < m; i++) {
            merged[k++] = nums2[i];
        }

        // Sort the merged array.
        Arrays.sort(merged);

        // Calculate the total number of elements in the merged array.
        int total = merged.length;

        if (total % 2 == 1) {
            // If the total number of elements is odd, return the middle element as the median.
            return (double) merged[total / 2];
        } else {
            // If the total number of elements is even, calculate the average of the two middle elements as the median.
            int middle1 = merged[total / 2 - 1];
            int middle2 = merged[total / 2];
            return ((double) middle1 + (double) middle2) / 2.0;
        }
    }
}

Code for Two-Pointer Method

C++
Java
Python
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n = nums1.length;
        int m = nums2.length;
        int i = 0, j = 0, m1 = 0, m2 = 0;

        // Find median.
        for (int count = 0; count <= (n + m) / 2; count++) {
            m2 = m1;
            if (i != n && j != m) {
                if (nums1[i] > nums2[j]) {
                    m1 = nums2[j++];
                } else {
                    m1 = nums1[i++];
                }
            } else if (i < n) {
                m1 = nums1[i++];
            } else {
                m1 = nums2[j++];
            }
        }

        // Check if the sum of n and m is odd.
        if ((n + m) % 2 == 1) {
            return (double) m1;
        } else {
            double ans = (double) m1 + (double) m2;
            return ans / 2.0;
        }
    }
}

Code for Binary Search

C++
Java
Python
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int n1 = nums1.length, n2 = nums2.length;
        
        // Ensure nums1 is the smaller array for simplicity
        if (n1 > n2)
            return findMedianSortedArrays(nums2, nums1);
        
        int n = n1 + n2;
        int left = (n1 + n2 + 1) / 2; // Calculate the left partition size
        int low = 0, high = n1;
        
        while (low <= high) {
            int mid1 = (low + high) >> 1; // Calculate mid index for nums1
            int mid2 = left - mid1; // Calculate mid index for nums2
            
            int l1 = Integer.MIN_VALUE, l2 = Integer.MIN_VALUE, r1 = Integer.MAX_VALUE, r2 = Integer.MAX_VALUE;
            
            // Determine values of l1, l2, r1, and r2
            if (mid1 < n1)
                r1 = nums1[mid1];
            if (mid2 < n2)
                r2 = nums2[mid2];
            if (mid1 - 1 >= 0)
                l1 = nums1[mid1 - 1];
            if (mid2 - 1 >= 0)
                l2 = nums2[mid2 - 1];
            
            if (l1 <= r2 && l2 <= r1) {
                // The partition is correct, we found the median
                if (n % 2 == 1)
                    return Math.max(l1, l2);
                else
                    return ((double)(Math.max(l1, l2) + Math.min(r1, r2))) / 2.0;
            }
            else if (l1 > r2) {
                // Move towards the left side of nums1
                high = mid1 - 1;
            }
            else {
                // Move towards the right side of nums1
                low = mid1 + 1;
            }
        }
        
        return 0; // If the code reaches here, the input arrays were not sorted.
    }
}

Comments

Popular posts from this blog

Difference between String ,StringBuffer & StringBuilder?

Run this simple java program and create scenerio of String object creation in your mind.You will see huge difference than expectation.                                I would recommend to first try on your own then follow the solution . As you execute the above line of codes in your Java Runtime Environment .As compiler read the lines .In  case of                                      String a= new String("Hello");        As it will allow compiler to create a new string object .It is always mandatory for  compiler to allocate a memory space in heap whenever new  keyword is used.So String class object created successfully in heap with reference variable a.And a very important point  need to be noted down that here  "new String("Hello');"   It will make a literal object in String  pool with value "Hello".So total number of object created equals two.so if you print value of a using System.out.println(a);  It will print

Design Discussion over Microservices Adaption

 Terms that are most commonly used in any microservices architecture Don't worry after watching so many new terms as below : Saga Pattern Bounded context Eventual consistency Event Command Execution  Event broker CDC (change data capture) event managment Domain driven design Event driven design CQRS (Command query responsibility segregation) Rollback operation  Asynchronous Callback operation Fault tolerance :Bulk Head & Circuit breaker Open API configurations Centralized logging ELK Stats aggregation Aggregates in Domain Driven Design FAT Domain VS Anemic Domain Ubiquitous Language  Event sourcing Event replay Scatter-Gather Pattern Saga Pattern:      A pattern which is the heart soul of any microservice architecture ,it is used to manage data consistency across multiple microservices in distributed transaction .It performs a sequence of local transactions which perform updation operation in services & publish a message or trigger the event. There are below three type of t

LOVE THE WAY SINGLETON PATTERN CAN BE DESIGNED ! WOWW...

To implement Singleton pattern, we have different approaches : 1.Eager initialization: In this method the instance of clss is created at loading time .As whenever in java there is a requirement of species at loading time we first remember of Static keyword. package com.questprogram.singleton; public class EagerInitializedSingleton { private static final EagerInitializedSingleton instance = new EagerInitializedSingleton(); //private constructor to avoid client applications to use constructor private EagerInitializedSingleton(){} public static EagerInitializedSingleton getInstance(){ return instance; } } 2. Static block initialization Static Block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling. package com.questprogram.singleton; public class StaticBlockSingleton { private static StaticBlockSingleton in