# Leetcode Median of Two Sorted Arrays problem solution in C++

Feb 11, 2023

In the Leetcode Median of Two Sorted Arrays problem solution in C++ programming 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)).

## Leetcode Median of Two Sorted Arrays problem solution in C++ programming

``````class Solution {
public:
double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) {

if(nums1.size() > nums2.size())
nums1.swap(nums2);

int n1 = nums1.size(), n2 = nums2.size();

int l = 0, h = n1;

while(l <= h){

int i1 = (l+h)/2;
int i2 = (n1+n2+1)/2 - i1;

int max1 = (i1 == 0  ? INT_MIN : nums1[i1-1]);
int max2 = (i2 == 0  ? INT_MIN : nums2[i2-1]);

int min1 = (i1 == n1 ? INT_MAX : nums1[i1]);
int min2 = (i2 == n2 ? INT_MAX :  nums2[i2]);

double maxl = max(max1,max2);
double minr = min(min1,min2);

if(maxl <= minr){
if((n1+n2)%2 == 0)
return (maxl+minr)/2;
return maxl;
}
else if(min1 < max2)
l = i1 + 1;
else
h = i1 - 1;
}
return 0;
}
};``````

#### By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.