VOOZH about

URL: https://www.geeksforgeeks.org/dsa/variants-of-binary-search/

⇱ Variants of Binary Search - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Variants of Binary Search

Last Updated : 11 Jul, 2025

Binary search is very easy right? Well, binary search can become complex when element duplication occurs in the sorted list of values. It's not always the "contains or not" we search using Binary Search, but there are 5 variants such as below:
1) Contains (True or False) 
2) Index of first occurrence of a key 
3) Index of last occurrence of a key 
4) Index of least element greater than key 
5) Index of greatest element less than key

Each of these searches, while the base logic remains same, have a minor variation in implementation and competitive coders should be aware of them. You might have seen other approaches such as this for finding first and last occurrence, where you compare adjacent element also for checking of first/last element is reached. 

From a complexity perspective, it may look like an O(log n) algorithm, but it doesn't work when the comparisons itself are expensive. A problem to prove this point is linked at the end of this post, feel free to try it out.
Variant 1: Contains key (True or False) 

Input : 2 3 3 5 5 5 6 6
Function : Contains(4)
Returns : False

Function : Contains(5)
Returns : True


Variant 2: First occurrence of key (index of array). This is similar to 

Input : 2 3 3 5 5 5 6 6
Function : first(3)
Returns : 1

Function : first(5)
Returns : 3

Function : first(4)
Returns : -1

Variant 3: Last occurrence of key (index of array) 

Input : 2 3 3 5 5 5 6 6
Function : last(3)
Returns : 2

Function : last(5)
Returns : 5

Function : last(4)
Returns : -1


Variant 4: index(first occurrence) of least integer greater than key. This is similar to 

Input : 2 3 3 5 5 5 6 6
Function : leastGreater(2)
Returns : 1

Function : leastGreater(5)
Returns : 6

Variant 5: index(last occurrence) of greatest integer lesser than key 

Input : 2 3 3 5 5 5 6 6
Function : greatestLesser(2)
Returns : -1

Function : greatestLesser(5)
Returns : 2


As you will see below, if you observe the clear difference between the implementations you will see that the same logic is used to find different variants of binary search.


Output: 
Contains
0 0
1 0
2 1
3 1
4 0
5 1
6 1
7 0
8 0
9 0
First occurrence of key
0 -1
1 -1
2 0
3 1
4 -1
5 3
6 6
7 -1
8 -1
9 -1
Last occurrence of key
0 -1
1 -1
2 0
3 2
4 -1
5 5
6 7
7 -1
8 -1
9 -1
Least integer greater than key
0 0
1 0
2 1
3 3
4 3
5 6
6 -1
7 -1
8 -1
9 -1
Greatest integer lesser than key
0 -1
1 -1
2 -1
3 0
4 2
5 2
6 5
7 7
8 7
9 7

 

Here is the problem I have mentioned at the beginning of the post: KCOMPRES problem in Codechef. Do try it out and feel free post your queries here.
More Binary Search Practice Problems
 


 

Comment
Article Tags: