Skip to content

Create soln of gfg hard median-of-2-sorted-arrays-of-different-sizes #1970

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jun 24, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@

---
id: median-of-2-sorted-arrays-of-different-sizes
title: Median of Two Sorted Arrays Problem (gfg)
sidebar_label: 0004 - Median of Two Sorted Arrays
tags:
- Intermediate
- Array
- Binary Search
- LeetCode
- CPP
- Python
- DSA
description: "This is a solution to the Median of Two Sorted Arrays problem on LeetCode."
---

This tutorial contains a complete walk-through of the Median of Two Sorted Arrays problem from the LeetCode website. It features the implementation of the solution code in two programming languages: Python and C++.

## Problem Description

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

## Examples

**Example 1:**

```
Input : array1 = [1, 3], array2 = [2]
Output : 2.0
Explanation : The median is 2.0.
```

**Example 2:**

```
Input : array1 = [1, 2], array2 = [3, 4]
Output : 2.5
Explanation : The median is (2 + 3)/2 = 2.5.
```

## Your Task

You don't need to read input or print anything. Your task is to complete the function `MedianOfArrays()` which takes the arrays `array1`, `array2` and their sizes `m` and `n` as inputs and return the median of the two sorted arrays.

Expected Time Complexity: $O(log(min(m, n)))$

Expected Auxiliary Space: $O(1)$

## Constraints

* `0 ≤ m, n ≤ 1000`
* `1 ≤ array1[i], array2[i] ≤ 1000000`

## Problem Explanation

The problem is to find the median of two sorted arrays. The median is the middle value in the sorted order of the combined array. If the total number of elements is even, the median is the average of the two middle numbers.

## Code Implementation

<Tabs>
<TabItem value="Python" label="Python" default>
<SolutionAuthor name="@YourUsername"/>

```py
class Solution:
def MedianOfArrays(self, array1, array2):
if len(array1) > len(array2):
array1, array2 = array2, array1

m, n = len(array1), len(array2)
imin, imax, half_len = 0, m, (m + n + 1) // 2

while imin <= imax:
i = (imin + imax) // 2
j = half_len - i

if i < m and array1[i] < array2[j-1]:
imin = i + 1
elif i > 0 and array1[i-1] > array2[j]:
imax = i - 1
else:
if i == 0: max_of_left = array2[j-1]
elif j == 0: max_of_left = array1[i-1]
else: max_of_left = max(array1[i-1], array2[j-1])

if (m + n) % 2 == 1:
return max_of_left

if i == m: min_of_right = array2[j]
elif j == n: min_of_right = array1[i]
else: min_of_right = min(array1[i], array2[j])

return (max_of_left + min_of_right) / 2.0
```

</TabItem>
<TabItem value="C++" label="C++">
<SolutionAuthor name="@YourUsername"/>

```cpp
#include <vector>
#include <algorithm>
#include <climits>
#include <stdexcept>
#include <iostream>

class Solution {
public:
double MedianOfArrays(std::vector<int>& array1, std::vector<int>& array2) {
if (array1.size() > array2.size()) {
return MedianOfArrays(array2, array1);
}

int m = array1.size();
int n = array2.size();
int low = 0, high = m;

while (low <= high) {
int partition1 = (low + high) / 2;
int partition2 = (m + n + 1) / 2 - partition1;

int maxLeft1 = (partition1 == 0) ? INT_MIN : array1[partition1 - 1];
int minRight1 = (partition1 == m) ? INT_MAX : array1[partition1];

int maxLeft2 = (partition2 == 0) ? INT_MIN : array2[partition2 - 1];
int minRight2 = (partition2 == n) ? INT_MAX : array2[partition2];

if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) {
if ((m + n) % 2 == 0) {
return (std::max(maxLeft1, maxLeft2) + std::min(minRight1, minRight2)) / 2.0;
} else {
return std::max(maxLeft1, maxLeft2);
}
} else if (maxLeft1 > minRight2) {
high = partition1 - 1;
} else {
low = partition1 + 1;
}
}

throw std::invalid_argument("Input arrays are not sorted");
}
};

// Example usage:
int main() {
std::vector<int> array1 = {1, 3};
std::vector<int> array2 = {2};

Solution sol;
double median = sol.MedianOfArrays(array1, array2);
std::cout << "Median: " << median << std::endl; // Expected output: 2.0

return 0;
}
```

</TabItem>
</Tabs>


## Example Walkthrough

For the arrays `array1 = [1, 3]` and `array2 = [2]`:

1. Combined array would be `[1, 2, 3]`.
2. The median is `2.0`.

For the arrays `array1 = [1, 2]` and `array2 = [3, 4]`:

1. Combined array would be `[1, 2, 3, 4]`.
2. The median is `(2 + 3) / 2 = 2.5`.

## Solution Logic:

1. Ensure `array1` is the smaller array to minimize the number of binary search steps.
2. Perform binary search on the smaller array.
3. Calculate partitions for both arrays such that left and right parts of the partitions can be merged to form the sorted order.
4. Handle edge cases where partitions are at the boundaries of the arrays.
5. If the total number of elements is even, the median is the average of the maximum of the left parts and the minimum of the right parts.
6. If the total number of elements is odd, the median is the maximum of the left parts.

## Time Complexity

* The primary operation is binary search, which has a time complexity of $O(log(min(m, n)))$, where m and n are the sizes of the arrays.

## Space Complexity

Auxiliary Space: The auxiliary space complexity is $O(1)$ because we are not using any extra space proportional to the size of the input arrays.

## References

- **gfg Problem:** [gfg Problem](https://www.geeksforgeeks.org/problems/median-of-2-sorted-arrays-of-different-sizes/1?itm_source=geeksforgeeks&itm_medium=article&itm_campaign=bottom_sticky_on_article)
- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/)
```

In this format, the tutorial includes a description of the problem, examples, expected time and space complexity, constraints, detailed problem explanation, and complete code implementations in both Python and C++. It ends with a walkthrough of examples to illustrate the logic of the solution.
Loading