Skip to content

Conversation

lkhanna1505
Copy link

This the best hard problem on leetcode for begineers.

I have solved it in Java and have got the runtime success rate of 100.0%.
Below is my thought process while solving it:-

Intuition

The problem asks for the median of two sorted arrays. My first thought is that since both arrays are sorted, we can merge them into a single sorted array and then directly find the median. This is similar to the merge step in merge sort.

Approach

  1. Merge the Arrays:
    Use two pointers to traverse both arrays and merge them into a new sorted array.
  2. Find the Median:
    • If the total number of elements is odd, the median is the middle element.
    • If it's even, the median is the average of the two middle elements.

This approach is straightforward and leverages the sorted property of the input arrays.

Complexity

  • Time complexity:
    $$O(m + n)$$
    where (m) and (n) are the lengths of the two input arrays. We have to process every element once to merge them.

  • Space complexity:
    $$O(m + n)$$
    because we create a new array to store the merged result.

Code

class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int m = nums1.length;
        int n = nums2.length;
        int[] merged = new int[m + n];
        
        int i = 0, j = 0, k = 0;
        
        // Merge the two sorted arrays
        while(i < m && j < n) {
            if(nums1[i] < nums2[j]) {
                merged[k++] = nums1[i++];
            } else {
                merged[k++] = nums2[j++];
            }
        }
        
        // Copy remaining elements
        while(i < m) merged[k++] = nums1[i++];
        while(j < n) merged[k++] = nums2[j++];
        
        // Find the median
        int total = m + n;
        if(total % 2 == 1) {
            return merged[total / 2];
        } else {
            return (merged[total / 2 - 1] + merged[total / 2]) / 2.0;
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant