My first Codeforces blog post! Hooray!
This post was inspired by the problem: E. Iva & Pav of Codeforces round 900 (https://codeforces.me/contest/1878/problem/E). This problem requires us to find the last element in the array such that the Bitwise AND values of all elements starting from the query index are greater than or equal to key value. The important takeaway of this problem is that the Bitwise AND value can only decrease after including another element. This permits us to use Binary Search, which brings us to our topic.
The Problem
Unfortunately being the newbie that I am, I tried applying basic binary search, lower bound and upper bound but didn't succeed. Here we are required to find the last element which satisfies the given condition thus requiring a slightly different binary search algorithm. This sparked my urge to dive deep into the bowel of Binary Search. So After years (about 0.01 years) of painstaking research I finally compiled a list of five algorithms that will satisfy most problems regarding binary search. It also lead to better my understanding of the binary search algorithm.
The Algorithms
The Basic Binary search algorithm only applies for arrays with distinct elements. If the array has multiple instances of one element we need to apply a different algorithm. For example you could need any of the following elements for your specific problem.
Ex- [1, 1, 1, 2, 2, 3, 4, 4, 4, 7, 7, 9] key = 4 ^ ^ ^ ^ | | | |
These are the five algorithms for ascending order and they all have their descending order counterparts as well.



