|
| 1 | + |
| 2 | +--- |
| 3 | +id: median-of-2-sorted-arrays-of-different-sizes |
| 4 | +title: Median of Two Sorted Arrays Problem (gfg) |
| 5 | +sidebar_label: 0004 - Median of Two Sorted Arrays |
| 6 | +tags: |
| 7 | + - Intermediate |
| 8 | + - Array |
| 9 | + - Binary Search |
| 10 | + - LeetCode |
| 11 | + - CPP |
| 12 | + - Python |
| 13 | + - DSA |
| 14 | +description: "This is a solution to the Median of Two Sorted Arrays problem on LeetCode." |
| 15 | +--- |
| 16 | + |
| 17 | +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++. |
| 18 | + |
| 19 | +## Problem Description |
| 20 | + |
| 21 | +Given two sorted arrays array1 and array2 of size m and n respectively, find the median of the two sorted arrays. |
| 22 | + |
| 23 | +## Examples |
| 24 | + |
| 25 | +**Example 1:** |
| 26 | + |
| 27 | +``` |
| 28 | +Input : array1 = [1, 3], array2 = [2] |
| 29 | +Output : 2.0 |
| 30 | +Explanation : The median is 2.0. |
| 31 | +``` |
| 32 | + |
| 33 | +**Example 2:** |
| 34 | + |
| 35 | +``` |
| 36 | +Input : array1 = [1, 2], array2 = [3, 4] |
| 37 | +Output : 2.5 |
| 38 | +Explanation : The median is (2 + 3)/2 = 2.5. |
| 39 | +``` |
| 40 | + |
| 41 | +## Your Task |
| 42 | + |
| 43 | +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. |
| 44 | + |
| 45 | +Expected Time Complexity: $O(log(min(m, n)))$ |
| 46 | + |
| 47 | +Expected Auxiliary Space: $O(1)$ |
| 48 | + |
| 49 | +## Constraints |
| 50 | + |
| 51 | +* `0 ≤ m, n ≤ 1000` |
| 52 | +* `1 ≤ array1[i], array2[i] ≤ 1000000` |
| 53 | + |
| 54 | +## Problem Explanation |
| 55 | + |
| 56 | +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. |
| 57 | + |
| 58 | +## Code Implementation |
| 59 | + |
| 60 | +<Tabs> |
| 61 | + <TabItem value="Python" label="Python" default> |
| 62 | + <SolutionAuthor name="@YourUsername"/> |
| 63 | + |
| 64 | + ```py |
| 65 | + class Solution: |
| 66 | + def MedianOfArrays(self, array1, array2): |
| 67 | + if len(array1) > len(array2): |
| 68 | + array1, array2 = array2, array1 |
| 69 | + |
| 70 | + m, n = len(array1), len(array2) |
| 71 | + imin, imax, half_len = 0, m, (m + n + 1) // 2 |
| 72 | + |
| 73 | + while imin <= imax: |
| 74 | + i = (imin + imax) // 2 |
| 75 | + j = half_len - i |
| 76 | + |
| 77 | + if i < m and array1[i] < array2[j-1]: |
| 78 | + imin = i + 1 |
| 79 | + elif i > 0 and array1[i-1] > array2[j]: |
| 80 | + imax = i - 1 |
| 81 | + else: |
| 82 | + if i == 0: max_of_left = array2[j-1] |
| 83 | + elif j == 0: max_of_left = array1[i-1] |
| 84 | + else: max_of_left = max(array1[i-1], array2[j-1]) |
| 85 | + |
| 86 | + if (m + n) % 2 == 1: |
| 87 | + return max_of_left |
| 88 | + |
| 89 | + if i == m: min_of_right = array2[j] |
| 90 | + elif j == n: min_of_right = array1[i] |
| 91 | + else: min_of_right = min(array1[i], array2[j]) |
| 92 | + |
| 93 | + return (max_of_left + min_of_right) / 2.0 |
| 94 | + ``` |
| 95 | + |
| 96 | + </TabItem> |
| 97 | + <TabItem value="C++" label="C++"> |
| 98 | + <SolutionAuthor name="@YourUsername"/> |
| 99 | + |
| 100 | + ```cpp |
| 101 | + #include <vector> |
| 102 | + #include <algorithm> |
| 103 | + #include <climits> |
| 104 | + #include <stdexcept> |
| 105 | + #include <iostream> |
| 106 | + |
| 107 | + class Solution { |
| 108 | + public: |
| 109 | + double MedianOfArrays(std::vector<int>& array1, std::vector<int>& array2) { |
| 110 | + if (array1.size() > array2.size()) { |
| 111 | + return MedianOfArrays(array2, array1); |
| 112 | + } |
| 113 | + |
| 114 | + int m = array1.size(); |
| 115 | + int n = array2.size(); |
| 116 | + int low = 0, high = m; |
| 117 | + |
| 118 | + while (low <= high) { |
| 119 | + int partition1 = (low + high) / 2; |
| 120 | + int partition2 = (m + n + 1) / 2 - partition1; |
| 121 | + |
| 122 | + int maxLeft1 = (partition1 == 0) ? INT_MIN : array1[partition1 - 1]; |
| 123 | + int minRight1 = (partition1 == m) ? INT_MAX : array1[partition1]; |
| 124 | + |
| 125 | + int maxLeft2 = (partition2 == 0) ? INT_MIN : array2[partition2 - 1]; |
| 126 | + int minRight2 = (partition2 == n) ? INT_MAX : array2[partition2]; |
| 127 | + |
| 128 | + if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) { |
| 129 | + if ((m + n) % 2 == 0) { |
| 130 | + return (std::max(maxLeft1, maxLeft2) + std::min(minRight1, minRight2)) / 2.0; |
| 131 | + } else { |
| 132 | + return std::max(maxLeft1, maxLeft2); |
| 133 | + } |
| 134 | + } else if (maxLeft1 > minRight2) { |
| 135 | + high = partition1 - 1; |
| 136 | + } else { |
| 137 | + low = partition1 + 1; |
| 138 | + } |
| 139 | + } |
| 140 | + |
| 141 | + throw std::invalid_argument("Input arrays are not sorted"); |
| 142 | + } |
| 143 | + }; |
| 144 | + |
| 145 | + // Example usage: |
| 146 | + int main() { |
| 147 | + std::vector<int> array1 = {1, 3}; |
| 148 | + std::vector<int> array2 = {2}; |
| 149 | + |
| 150 | + Solution sol; |
| 151 | + double median = sol.MedianOfArrays(array1, array2); |
| 152 | + std::cout << "Median: " << median << std::endl; // Expected output: 2.0 |
| 153 | + |
| 154 | + return 0; |
| 155 | + } |
| 156 | + ``` |
| 157 | + |
| 158 | + </TabItem> |
| 159 | +</Tabs> |
| 160 | + |
| 161 | + |
| 162 | +## Example Walkthrough |
| 163 | + |
| 164 | +For the arrays `array1 = [1, 3]` and `array2 = [2]`: |
| 165 | + |
| 166 | +1. Combined array would be `[1, 2, 3]`. |
| 167 | +2. The median is `2.0`. |
| 168 | + |
| 169 | +For the arrays `array1 = [1, 2]` and `array2 = [3, 4]`: |
| 170 | + |
| 171 | +1. Combined array would be `[1, 2, 3, 4]`. |
| 172 | +2. The median is `(2 + 3) / 2 = 2.5`. |
| 173 | + |
| 174 | +## Solution Logic: |
| 175 | + |
| 176 | +1. Ensure `array1` is the smaller array to minimize the number of binary search steps. |
| 177 | +2. Perform binary search on the smaller array. |
| 178 | +3. Calculate partitions for both arrays such that left and right parts of the partitions can be merged to form the sorted order. |
| 179 | +4. Handle edge cases where partitions are at the boundaries of the arrays. |
| 180 | +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. |
| 181 | +6. If the total number of elements is odd, the median is the maximum of the left parts. |
| 182 | + |
| 183 | +## Time Complexity |
| 184 | + |
| 185 | +* 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. |
| 186 | + |
| 187 | +## Space Complexity |
| 188 | + |
| 189 | +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. |
| 190 | + |
| 191 | +## References |
| 192 | + |
| 193 | +- **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) |
| 194 | +- **Solution Author:** [arunimad6yuq](https://www.geeksforgeeks.org/user/arunimad6yuq/) |
| 195 | +``` |
| 196 | + |
| 197 | +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. |
0 commit comments