Skip to content

Median of Two Sorted Arrays - With Detailed Explanation #163

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 14, 2021

Conversation

vedic-kalra
Copy link
Contributor

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

  • [x ] New feature/solution added

Checklist:

  • My code follows the style guidelines(Clean Code) of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • [] I have created a helpful and easy to understand README.md
  • [] I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • [] I have updated the readme with tick in question in appropriate language.

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 pranjay-poddar#134
Copy link
Owner

@pranjay-poddar pranjay-poddar left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for contributing

@pranjay-poddar pranjay-poddar merged commit f215ea4 into pranjay-poddar:master Oct 14, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants