Binary Search

99% of binary search problems that you see online will fall into 1 of these 3 templates.

Note:The templates and their differences have been colored coded below.

If we have sorted array, we can perform binary search. We go into the middle of array, if equal, we found it, if smaller, go left, if bigger go right.

It is used to search for an element or condition which requires accessing the current index and its immediate right neighbor's index in the array.

This is used when requires accessing the current index and its immediate left and right neighbor's index in the array.

We use binary search for finding k index of a value that is opposite to what is at position i and j. So we calculate -arr[i] - arr[j] and then we search for this value in the array. That means -arr[i] - arr[i] + arr[k] is equal to 0.

O(n^2 n log(n)), definitelly better than O(n^3).

Here is another implementation of the problem.

Last updated

Was this helpful?