Often when trying to solve a problem involving Binary Search or 2-Pointer Technique, I make off by one errors, and/or fail to handle edge cases. Even if I know that my solution might fail on a particular edge case, to correct it takes a lot of time. I would like to know a method/implementation, such that I can code up the solutions without having to worry about edge cases, etc. For Binary Search, I know of one such method where to avoid infinite loop, we can use the following code: Say we want to find the maximum index in an array which satisfies certain property -->
while(hi-lo>1)
{
int mid=(lo+hi)/2;
int chk=check(SOME CONDITION);
if(chk==1) lo=mid;
else hi=mid-1;
}
int ans;
if(check(SOME CONDITION)==1) ans=hi;
else mid=lo;
If any better approach is available(for Binary Search), you are welcome to comment. Also, can you give a good implementation for 2 — Pointer Technique. You can find an easy problem involving one or both of these techniques here --> http://mirror.codeforces.com/contest/762/problem/C.
Thanks in advance.