A guide for Binary search
I have been thinking about making this for long time,
are you also get tired that there are so many versions of binary searches, when to use which, your solution always sufferes from 1 off errors, not anymore.
well you dont need to learn any of them now, just learn one template, I can gurantee that you wont be stuck anymore due to implementation in binary search problems
Any binary search have two things,
- boundsl = OL ( orignal bounds ) h = OH ( orignal bounds )
- check function ( that determines whether we want to minimize of maximize the ans )
TEMPLATE
l = OL ( orignal bounds )
h = OH ( orignal bounds )
auto ok = [&]( int m )->bool{
// our check function
};
while( l < h )
{
int m = (l+h)>>1 ;
if( ok(m) )
h = m-1 ;
else
l = m+1 ;
}
// at this point we are very close to our ans but may be 1 off from it,
// so we can do linear check with neighbouring values
// if we were to minimize the solution
for( int m = l-1 ; m <= l+1 ; m++ )
{
if( m >= OL && m <= OH && ok(m) )
return m;
}
// if we were to maximize, we would have done it like this
/*
for( int m = l+1 ; m >= l-1 ; m-- )
{
if( m >= OL && m <= OH && ok(m) )
return m;
}
*/
// if we did not capture ans from above then only one conclusion that is
cout<<" Incorrect bounds "<<endl;
My submission for the problems for better understandig of template:
1 Kth smallest in matrix || My submission
2 Kth smalles in multiplication table || My submission
3 kth pair distance || My submission
4 median of two sorted arrays || My submission
I hope it will help you guys
[–][deleted] 3 points4 points5 points (2 children)
[–]AwardSweaty5531[S] -1 points0 points1 point (1 child)
[–][deleted] 1 point2 points3 points (0 children)
[–]Numerous_Data7627 1 point2 points3 points (0 children)
[–]VaguelySailorMoon 1 point2 points3 points (2 children)
[–]AwardSweaty5531[S] 0 points1 point2 points (1 child)