Skip to content
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

MedianOfTwoSortedArrayOfDifferentLength.java #302

Open
kavinda14 opened this issue Nov 3, 2020 · 1 comment
Open

MedianOfTwoSortedArrayOfDifferentLength.java #302

kavinda14 opened this issue Nov 3, 2020 · 1 comment

Comments

@kavinda14
Copy link

Could someone tell me why input2 has to be longer in length than input1?

I did some examples by hand and this is definitely right, but I am failing to understand the logic behind it.
Is it because when input2 is longer, there is more flexibility in moving the partitions around?

if (input1.length > input2.length) { return findMedianSortedArrays(input2, input1); }

@r0b0ji
Copy link

r0b0ji commented Nov 9, 2020

It DOES NOT have to be this way. It is done this way for optimization. You can verify by commenting out those 3 lines at top and it will still work.

He is doing sort of binary search on input1, so he make sure input1 is smaller one. If both are of similar length and is not much different in length it doesn't matter. But think about skewed case when one is of length 10 vs another of length 10000. Then obviously, the median will be median of 5005th and 5006th element. If you pick longer one as first and do binary search it will take many more steps to reach final answer than if you chose smaller one for doing binary search.

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

No branches or pull requests

2 participants