# Why do I get a runtime error

• This code is working find on my local machine , but I get a runtime error for this input

[1], [2,3,4,5,6,7]. My approach is as follows

If the smallest element of either array is larger than the biggest element of the other array, then calculate the median position ( m+n/2)
Depending on array sizes, figure out which array the median lies in and the exact index.
Also if total number of elements is even , median will be avg of the 2 center most elements else it is the center most element itself.

if the above condition does not match then start traversing both arrays,(again median position = m+n /2 ). Increment the index pointer for the array which has the smaller element. Keep traversing till the current sum of the indexes < = median position. Now calculate the median based on whether total number of elements is even or odd.

For the test case which fails I get the corrent answer "4" on my machine , not sure why I get a runtime error through the OJ

class Solution {
public:
double findMedianSortedArrays(int A[], int m, int B[], int n) {
//cout<<"Inside median function"<<"\n";
int mid_ind;
double median;
//cout<<"lengths : "<<m<<","<<n<<"\n";
if(A[m]<B[0]){
if((m+n)%2){
mid_ind = ((m+n)/2);
median = mid_ind > m? double(B[mid_ind-m]) : double(A[mid_ind]);
return median;
}else{
mid_ind = ((m+n)/2);
if(mid_ind>m){
median = (B[mid_ind-m]+B[mid_ind-m-1])/2.0;
}
else if(mid_ind<m){
median = (A[mid_ind]+A[mid_ind+1])/2.0;
}
else{
median = (A[m]+B[0])/2;
}
return median;
}
}
else if(B[n]<A[0]){
if((m+n)%2){
mid_ind = ((m+n)/2);
median = mid_ind > m? double(A[mid_ind-n]) : double(B[mid_ind]);
return median;
}else{
mid_ind = ((m+n)/2);
if(mid_ind>n){
median = (A[mid_ind-n]+A[mid_ind-n-1])/2.0;
}
else if(mid_ind<n){
median = (B[mid_ind]+B[mid_ind+1])/2.0;
}
else{
median = (B[n]+A[0])/2.0;
}
return median;
}
}else{
if((m+n)%2){
mid_ind = ((m+n)/2);
}else{
mid_ind = ((m+n)/2)-1;
}
int i,j=0;
while(i+j < mid_ind){
if(A[i]>B[j]){
i++;
}
if(B[j]>A[i]){
j++;
}
if(A[i] == B[j]){
i++;
if(i+j+1<mid_ind){
j++;
}
}
}

if((m+n)%2){
median = i>j?A[i]:B[j];
}else{
median = (A[i]+B[j])/2.0;
}
return median;

}

return 0 ;
}
};

• I found in your code, you use m and n as last index, but actually they are lengths, please check A[m] and B[n].

• thanks, that was definitely 1 of the errors

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.