pranjay-poddar / Data-Structures-And-Algorithms

Important data structure and algorithms codes and concept's open-source repository.
https://bit.ly/30DLzuJ
MIT License
48 stars 109 forks source link

4. Median of Two Sorted Arrays #145

Open vedic-kalra opened 2 years ago

vedic-kalra commented 2 years ago

Updated solution: Variant of binary search in C++, 14[ms] ; O(lg(m+n)) Easy to understand with explanation.

Description

Suppose the two arrays are A and B. Perform the following variant of binary search first in A then B to find the median.

Start from low = 0, high = |A|, guess i = floor (low + high)/2 For the median m, there should be total half = floor (|A| + |B| + 1) / 2 elements not greater than it. Since there are i + 1 elements not greater than A[i] in A, There should be half - (i + 1) elements not greater than A[i] in B. Denote j = half - i - 2, thus we can compare if B[j] <= A[i] <= B[j + 1] is satisfied. This indicates That the guess is the correct median.

Otherwise, we can easily tell if the guess is too small or too big, then halve the elements to adjust the guess.

Fixes #134

Type of change

Checklist:

vedic-kalra commented 2 years ago

Resolved it in new PR #163