Median of Two Sorted Arrays Leetcode Solution
Median of Two Sorted Arrays Leetcode Problem :
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two sorted arrays.
The overall run time complexity should be O(log (m+n).
Example :
Input: nums1 = [1,3], nums2 = [2]
Output: 2.00000
Explanation: merged array = [1,2,3] and median is 2.
Median of Two Sorted Arrays Leetcode Solution :
Constraints :
- nums1.length == m
- nums2.length == n
- 0 <= m <= 1000
- 0 <= n <= 1000
- 1 <= m + n <= 2000
- -106 <= nums1[i], nums2[i] <= 10^6
Example 1:
- Input: nums1 = [1,2], nums2 = [3,4]
- Output: 2.50000
Approach :
- 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.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Code :
C++
Java
Python
C++
class Solution { public: double findMedianSortedArrays(vector< int>& nums1, vector< int>& nums2) { int n = nums1.size(); int m = nums2.size(); vector< int> merged; for (int i = 0; i < n; i++) { merged.push_back(nums1[i]); } for (int i = 0; i < m; i++) { merged.push_back(nums2[i]); } sort(merged.begin(), merged.end()); int total = merged.size(); if (total % 2 == 1) { return static_cast(merged[total / 2]); } else { int middle1 = merged[total / 2 - 1]; int middle2 = merged[total / 2]; return (static_cast< double>(middle1) + static_cast< double>(middle2)) / 2.0; } } };
Java
import java.util.Arrays; class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { int n = nums1.length; int m = nums2.length; 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]; } Arrays.sort(merged); int total = merged.length; if (total % 2 == 1) { return (double) merged[total / 2]; } else { int middle1 = merged[total / 2 - 1]; int middle2 = merged[total / 2]; return ((double) middle1 + (double) middle2) / 2.0; } } }
Python
class Solution: def findMedianSortedArrays(self, nums1, nums2): merged = nums1 + nums2 merged.sort() total = len(merged) if total % 2 == 1: return float(merged[total // 2]) else: middle1 = merged[total // 2 - 1] middle2 = merged[total // 2] return (float(middle1) + float(middle2)) / 2.0
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others