The Ubiquitous Binary Search | Set 1
Last Updated :
07 May, 2024
We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, “I sincerely attempt to solve the problem and ensure there are no corner cases”. After reading each problem, minimize the browser and try solving it.
Problem Statement: Given a sorted array of N distinct elements, find a key in the array using the least number of comparisons. (Do you think binary search is optimal to search a key in sorted array?) Without much theory, here is typical binary search algorithm.
C++
// Returns location of key, or -1 if not found
int BinarySearch(int A[], int l, int r, int key){
int m;
while( l <= r ){
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
C
// Returns location of key, or -1 if not found
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( l <= r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
Java
// Java code to implement the approach
import java.util.*;
class GFG {
// Returns location of key, or -1 if not found
static int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( l < r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
}
// This code is contributed by sanjoy_62.
Python
# Returns location of key, or -1 if not found
def BinarySearch(A, l, r, key):
while (l < r):
m = l + (r - l) // 2
if A[m] == key: #first comparison
return m
if A[m] < key: # second comparison
l = m + 1
else:
r = m - 1
return -1
""" This code is contributed by Rajat Kumar """
C#
// C# program to implement
// the above approach
using System;
class GFG
{
// Returns location of key, or -1 if not found
static int BinarySearch(int[] A, int l, int r, int key)
{
int m;
while( l < r )
{
m = l + (r-l)/2;
if( A[m] == key ) // first comparison
return m;
if( A[m] < key ) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
}
// This code is contributed by code_hunt.
JavaScript
<script>
// Javascript code to implement the approach
// Returns location of key, or -1 if not found
function BinarySearch(A, l, r, key) {
let m;
while (l < r) {
m = l + (r - l) / 2;
if (A[m] == key) // first comparison
return m;
if (A[m] < key) // second comparison
l = m + 1;
else
r = m - 1;
}
return -1;
}
// This code is contributed by gfgking
</script>
Theoretically we need log N + 1 comparisons in worst case. If we observe, we are using two comparisons per iteration except during final successful match, if any. In practice, comparison would be costly operation, it won’t be just primitive type comparison. It is more economical to minimize comparisons as that of theoretical limit. See below figure on initialize of indices in the next implementation.
The following implementation uses fewer number of comparisons.
C++
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r-l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
//this code is contributed by aditya942003patil
C
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r-l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
Java
// Java function for above algorithm
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int A[], int l, int r, int key)
{
int m;
while( r - l k > 1 )
{
m = l + k(r - l)/2;
if( A[m]k <= key )
l = km;
elsek
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
//this code is contributed by Akshay Tripathi(akshaytripathi630)
Python
# Invariant: A[l] <= key and A[r] > key
# Boundary: |r - l| = 1
# Input: A[l .... r-1]
def BinarySearch(A, l, r, key):
while (r-l > 1):
m = l+(r-l)//2
if A[m] <= key:
l = m
else:
r = m
if A[l] == key:
return l
if A[r] == key:
return r
return -1
""" Code is written by Rajat Kumar"""
C#
// C# conversion
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
int BinarySearch(int[] A, int l, int r, int key)
{
int m;
while (r - l > 1) {
m = l + (r - l) / 2;
if (A[m] <= key)
l = m;
else
r = m;
}
if (A[l] == key)
return l;
if (A[r] == key)
return r;
else
return -1;
}
// This code is contributed by akashish__
JavaScript
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
function BinarySearch(A, l, r, key)
{
let m;
while( r - l > 1 )
{
m = l + (r-l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
if( A[l] == key )
return l;
if( A[r] == key )
return r;
else
return -1;
}
In the while loop we are depending only on one comparison. The search space converges to place l and r point two different consecutive elements. We need one more comparison to trace search status. You can see sample test case http://ideone.com/76bad0. (C++11 code)
Problem Statement: Given an array of N distinct integers, find floor value of input ‘key’. Say, A = {-1, 2, 3, 5, 6, 8, 9, 10} and key = 7, we should return 6 as outcome. We can use the above optimized implementation to find floor value of key. We keep moving the left pointer to right most as long as the invariant holds. Eventually left pointer points an element less than or equal to key (by definition floor value). The following are possible corner cases, —> If all elements in the array are smaller than key, left pointer moves till last element. —> If all elements in the array are greater than key, it is an error condition. —> If all elements in the array equal and <= key, it is worst case input to our implementation.
Here is implementation,
C++
// largest value <= key
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
int Floor(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return A[l];
}
// Initial call
int Floor(int A[], int size, int key)
{
// Add error checking if key < A[0]
if( key < A[0] )
return -1;
// Observe boundaries
return Floor(A, 0, size, key);
}
//this code is contributed by aditya942003patil
C
// largest value <= key
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
int Floor(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return A[l];
}
// Initial call
int Floor(int A[], int size, int key)
{
// Add error checking if key < A[0]
if( key < A[0] )
return -1;
// Observe boundaries
return Floor(A, 0, size, key);
}
Java
public class Floor {
// This function returns the largest value in A that is
// less than or equal to key. Invariant: A[l] <= key and
// A[r] > key Boundary: |r - l| = 1 Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
static int floor(int[] A, int l, int r, int key)
{
int m;
while (r - l > 1) {
m = l + (r - l) / 2;
if (A[m] <= key)
l = m;
else
r = m;
}
return A[l];
}
// Initial call
static int floor(int[] A, int size, int key)
{
// Add error checking if key < A[0]
if (key < A[0])
return -1;
// Observe boundaries
return floor(A, 0, size, key);
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
System.out.println(floor(arr, arr.length - 1, 3));
}
}
Python
# largest value <= key
# Invariant: A[l] <= key and A[r] > key
# Boundary: |r - l| = 1
# Input: A[l .... r-1]
# Precondition: A[l] <= key <= A[r]
def Floor(A,l,r,key):
while (r-l>1):
m=l+(r-l)//2
if A[m]<=key:
l=m
else:
r=m
return A[l]
# Initial call
def Floor(A,size,key):
# Add error checking if key < A[0]
if key<A[0]:
return -1
# Observe boundaries
return Floor(A,0,size,key)
"""Code is written by Rajat Kumar"""
C#
using System;
public class Floor {
// This function returns the largest value in A that is
// less than or equal to key. Invariant: A[l] <= key and
// A[r] > key Boundary: |r - l| = 1 Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
static int floor(int[] A, int l, int r, int key)
{
int m;
while (r - l > 1) {
m = l + (r - l) / 2;
if (A[m] <= key)
l = m;
else
r = m;
}
return A[l];
}
// Initial call
static int floor(int[] A, int size, int key)
{
// Add error checking if key < A[0]
if (key < A[0])
return -1;
// Observe boundaries
return floor(A, 0, size, key);
}
public static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
Console.WriteLine(floor(arr, arr.Length - 1, 3));
}
}
// This code is contributed by sarojmcy2e
JavaScript
// largest value <= key
// Invariant: A[l] <= key and A[r] > key
// Boundary: |r - l| = 1
// Input: A[l .... r-1]
// Precondition: A[l] <= key <= A[r]
function Floor(A, l, r, key){
let m;
while(r - l > 1){
m = l + parseInt((r-l)/2);
if(A[m] <= key) l = m;
else r = m;
}
return A[l];
}
// Initial call
function Floor(A, size, key)
{
// Add error checking if key < A[0]
if( key < A[0] )
return -1;
// Observe boundaries
return Floor(A, 0, size, key);
}
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGAWRAL2852002)
You can see some test cases http://ideone.com/z0Kx4a.
Problem Statement: Given a sorted array with possible duplicate elements. Find number of occurrences of input ‘key’ in log N time. The idea here is finding left and right most occurrences of key in the array using binary search. We can modify floor function to trace right most occurrence and left most occurrence.
Here is implementation,
C++
#include <iostream>
// Input: Indices Range [l ... r)
// Invariant: A[l] <= key and A[r] > key
int GetRightPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return l;
}
// Input: Indices Range (l ... r]
// Invariant: A[r] >= key and A[l] > key
int GetLeftPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] >= key )
r = m;
else
l = m;
}
return r;
}
int CountOccurrences(int A[], int size, int key)
{
// Observe boundary conditions
int left = GetLeftPosition(A, -1, size-1, key);
int right = GetRightPosition(A, 0, size, key);
// What if the element doesn't exists in the array?
// The checks helps to trace that element exists
return (A[left] == key && key == A[right])?
(right - left + 1) : 0;
}
int main()
{
int A[] = {1, 1, 2, 3, 3, 3, 3, 3, 4, 4, 5};
int size = sizeof(A) / sizeof(A[0]);
int key = 3;
std::cout << "Number of occurances of " << key << ": " << CountOccurances(A, size, key) << std::endl;
return 0;
}
//code is written by khushboogoyal499
C
// Input: Indices Range [l ... r)
// Invariant: A[l] <= key and A[r] > key
int GetRightPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] <= key )
l = m;
else
r = m;
}
return l;
}
// Input: Indices Range (l ... r]
// Invariant: A[r] >= key and A[l] > key
int GetLeftPosition(int A[], int l, int r, int key)
{
int m;
while( r - l > 1 )
{
m = l + (r - l)/2;
if( A[m] >= key )
r = m;
else
l = m;
}
return r;
}
int CountOccurrences(int A[], int size, int key)
{
// Observe boundary conditions
int left = GetLeftPosition(A, -1, size-1, key);
int right = GetRightPosition(A, 0, size, key);
// What if the element doesn't exists in the array?
// The checks helps to trace that element exists
return (A[left] == key && key == A[right])?
(right - left + 1) : 0;
}
Java
public class OccurrencesInSortedArray {
// Returns the index of the leftmost occurrence of the
// given key in the array
private static int getLeftPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1) {
int mid = left + (right - left) / 2;
if (arr[mid] >= key) {
right = mid;
}
else {
left = mid;
}
}
return right;
}
// Returns the index of the rightmost occurrence of the
// given key in the array
private static int getRightPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1) {
int mid = left + (right - left) / 2;
if (arr[mid] <= key) {
left = mid;
}
else {
right = mid;
}
}
return left;
}
// Returns the count of occurrences of the given key in
// the array
public static int countOccurrences(int[] arr, int key)
{
int left
= getLeftPosition(arr, -1, arr.length - 1, key);
int right
= getRightPosition(arr, 0, arr.length, key);
if (arr[left] == key && key == arr[right]) {
return right - left + 1;
}
return 0;
}
public static void main(String[] args)
{
int[] arr = { 1, 2, 2, 2, 3, 4, 4, 5, 5 };
int key = 2;
System.out.println(
countOccurrences(arr, key)); // Output: 3
}
}
Python
# Input: Indices Range [l ... r)
# Invariant: A[l] <= key and A[r] > key
def GetRightPosition(A,l,r,key):
while r-l>1:
m=l+(r-l)//2
if A[m]<=key:
l=m
else:
r=m
return l
# Input: Indices Range (l ... r]
# Invariant: A[r] >= key and A[l] > key
def GetLeftPosition(A,l,r,key):
while r-l>1:
m=l+(r-l)//2
if A[m]>=key:
r=m
else:
l=m
return r
def countOccurrences(A,size,key):
#Observe boundary conditions
left=GetLeftPosition(A,-1,size-1,key)
right=GetRightPosition(A,0,size,key)
# What if the element doesn't exists in the array?
# The checks helps to trace that element exists
if A[left]==key and key==A[right]:
return right-left+1
return 0
"""Code is written by Rajat Kumar"""
C#
using System;
public class OccurrencesInSortedArray
{
// Returns the index of the leftmost occurrence of the
// given key in the array
private static int getLeftPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1)
{
int mid = left + (right - left) / 2;
if (arr[mid] >= key)
{
right = mid;
}
else
{
left = mid;
}
}
return right;
}
// Returns the index of the rightmost occurrence of the
// given key in the array
private static int getRightPosition(int[] arr, int left,
int right, int key)
{
while (right - left > 1)
{
int mid = left + (right - left) / 2;
if (arr[mid] <= key)
{
left = mid;
}
else
{
right = mid;
}
}
return left;
}
// Returns the count of occurrences of the given key in
// the array
public static int countOccurrences(int[] arr, int key)
{
int left = getLeftPosition(arr, -1, arr.Length - 1, key);
int right = getRightPosition(arr, 0, arr.Length, key);
if (arr[left] == key && key == arr[right])
{
return right - left + 1;
}
return 0;
}
public static void Main(string[] args)
{
int[] arr = { 1, 2, 2, 2, 3, 4, 4, 5, 5 };
int key = 2;
Console.WriteLine(countOccurrences(arr, key)); // Output: 3
}
}
JavaScript
// Input: Indices Range [l ... r)
// Invariant: A[l] <= key and A[r] > key
function getRightPosition(A, l, r, key) {
while (r - l > 1) {
const m = l + Math.floor((r - l) / 2);
if (A[m] <= key) {
l = m;
} else {
r = m;
}
}
return l;
}
// Input: Indices Range (l ... r]
// Invariant: A[r] >= key and A[l] > key
function getLeftPosition(A, l, r, key) {
while (r - l > 1) {
const m = l + Math.floor((r - l) / 2);
if (A[m] >= key) {
r = m;
} else {
l = m;
}
}
return r;
}
function countOccurrences(A, size, key) {
// Observe boundary conditions
let left = getLeftPosition(A, -1, size - 1, key);
let right = getRightPosition(A, 0, size, key);
// What if the element doesn't exist in the array?
// The checks help to determine whether the element exists
if (A[left] === key && key === A[right]) {
return right - left + 1;
}
return 0;
}
// Example usage
const A = [1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 6];
const key = 4;
const size = A.length;
const occurrences = countOccurrences(A, size, key);
console.log(`The number of occurrences of ${key} is: ${occurrences}`);
Sample code http://ideone.com/zn6R6a.
Problem Statement: Given a sorted array of distinct elements, and the array is rotated at an unknown position. Find minimum element in the array. We can see pictorial representation of sample input array in the below figure.
We converge the search space till l and r points single element. If the middle location falls in the first pulse, the condition A[m] < A[r] doesn’t satisfy, we converge our search space to A[m+1 … r]. If the middle location falls in the second pulse, the condition A[m] < A[r] satisfied, we converge our search space to A[1 … m]. At every iteration we check for search space size, if it is 1, we are done.
Given below is implementation of algorithm. Can you come up with different implementation?
C++
int BinarySearchIndexOfMinimumRotatedArray(int A[], int l, int r)
{
// extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if( A[l] >= A[r] )
return l;
while( l <= r )
{
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if( l == r )
return l;
m = l + (r-l)/2; // 'm' can fall in first pulse,
// second pulse or exactly in the middle
if( A[m] < A[r] )
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
else
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m+1;
}
return -1;
}
int BinarySearchIndexOfMinimumRotatedArray(int A[], int size)
{
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);
}
//this code is contributed by aditya942003patil
C
int BinarySearchIndexOfMinimumRotatedArray(int A[], int l, int r)
{
// extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if( A[l] <= A[r] )
return l;
while( l <= r )
{
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if( l == r )
return l;
m = l + (r-l)/2; // 'm' can fall in first pulse,
// second pulse or exactly in the middle
if( A[m] < A[r] )
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
else
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m+1;
}
return -1;
}
int BinarySearchIndexOfMinimumRotatedArray(int A[], int size)
{
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);
}
Java
public static int binarySearchIndexOfMinimumRotatedArray(int A[], int l, int r)
{
// extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if (A[l] >= A[r]) {
return l;
}
while (l <= r) {
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if (l == r) {
return l;
}
m = l + (r - l) / 2;
if (A[m] < A[r]) {
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
} else {
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m + 1;
}
}
return -1;
}
public static int binarySearchIndexOfMinimumRotatedArray(int A[], int size) {
return binarySearchIndexOfMinimumRotatedArray(A, 0, size - 1);
}
Python
def BinarySearchIndexOfMinimumRotatedArray(A, l, r):
# extreme condition, size zero or size two
# Precondition: A[l] > A[r]
if A[l] >= A[r]:
return l
while (l <= r):
# Termination condition (l will eventually falls on r, and r always
# point minimum possible value)
if l == r:
return l
m = l+(r-l)//2 # 'm' can fall in first pulse,
# second pulse or exactly in the middle
if A[m] < A[r]:
# min can't be in the range
# (m < i <= r), we can exclude A[m+1 ... r]
r = m
else:
# min must be in the range (m < i <= r),
# we must search in A[m+1 ... r]
l = m+1
return -1
def BinarySearchIndexOfMinimumRotatedArray(A, size):
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1)
"""Code is written by Rajat Kumar"""
C#
using System;
public class Program
{
public static int BinarySearchIndexOfMinimumRotatedArray(int[] A, int l, int r)
{
// Extreme condition, size zero or size two
int m;
// Precondition: A[l] > A[r]
if (A[l] >= A[r])
{
return l;
}
while (l <= r)
{
// Termination condition (l will eventually fall on r, and r always
// points to the minimum possible value)
if (l == r)
{
return l;
}
m = l + (r - l) / 2;
if (A[m] < A[r])
{
// Minimum can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
}
else
{
// Minimum must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m + 1;
}
}
return -1;
}
public static int BinarySearchIndexOfMinimumRotatedArray(int[] A, int size)
{
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size - 1);
}
public static void Main()
{
int[] A = { 6, 7, 8, 9, 1, 2, 3, 4, 5 };
int size = A.Length;
int minIndex = BinarySearchIndexOfMinimumRotatedArray(A, size);
Console.WriteLine("The index of the minimum element in the rotated array is: " + minIndex);
}
}
JavaScript
function BinarySearchIndexOfMinimumRotatedArray(A, l, r){
// extreme condition, size zero or size two
let m;
// Precondition: A[l] > A[r]
if(A[l] <= A[r]) return l;
while(l <= r){
// Termination condition (l will eventually falls on r, and r always
// point minimum possible value)
if(l == r) return l;
m = l + (r-l)/2;
if(A[m] < A[r]){
// min can't be in the range
// (m < i <= r), we can exclude A[m+1 ... r]
r = m;
}else{
// min must be in the range (m < i <= r),
// we must search in A[m+1 ... r]
l = m+1;
}
}
return -1;
}
function BinarySearchIndexOfMinimumRotatedArray(A, size){
return BinarySearchIndexOfMinimumRotatedArray(A, 0, size-1);
}
See sample test cases http://ideone.com/KbwDrk.
Exercises:
1. A function called signum(x, y) is defined as,
signum(x, y) = -1 if x < y
= 0 if x = y
= 1 if x > y
Did you come across any instruction set in which a comparison behaves like signum function? Can it make the first implementation of binary search optimal?
2. Implement ceil function replica of floor function.
3. Discuss with your friends “Is binary search optimal (results in the least number of comparisons)? Why not ternary search or interpolation search on a sorted array? When do you prefer ternary or interpolation search over binary search?”
4. Draw a tree representation of binary search (believe me, it helps you a lot to understand much internals of binary search).
Stay tuned, I will cover few more interesting problems using binary search in upcoming articles. I welcome your comments. – – – by Venki.
Similar Reads
Searching Algorithms
Searching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
3 min read
Most Common Searching Algorithms
Linear Search Algorithm
Given an array, arr of n integers, and an integer element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesn't exist. Input: arr[] = [1, 2, 3, 4], x = 3Output: 2Explanation: There is one test case with array as [1, 2, 3 4]
9 min read
Binary Search Algorithm - Iterative and Recursive Implementation
Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Conditions to apply Binary Search Algorithm in a Data S
15+ min read
Other Searching Algorithms
Sentinel Linear Search
Sentinel Linear Search as the name suggests is a type of Linear Search where the number of comparisons is reduced as compared to a traditional linear search. In a traditional linear search, only N comparisons are made, and in a Sentinel Linear Search, the sentinel value is used to avoid any out-of-b
7 min read
Meta Binary Search | One-Sided Binary Search
Meta binary search (also called one-sided binary search by Steven Skiena in The Algorithm Design Manual on page 134) is a modified form of binary search that incrementally constructs the index of the target value in the array. Like normal binary search, meta binary search takes O(log n) time. Meta B
9 min read
Ternary Search
Computer systems use different methods to find specific data. There are various search algorithms, each better suited for certain situations. For instance, a binary search divides information into two parts, while a ternary search does the same but into three equal parts. It's worth noting that tern
15+ min read
Jump Search
Like Binary Search, Jump Search is a searching algorithm for sorted arrays. The basic idea is to check fewer elements (than linear search) by jumping ahead by fixed steps or skipping some elements in place of searching all elements.For example, suppose we have an array arr[] of size n and a block (t
11 min read
Interpolation Search
Given a sorted array of n uniformly distributed values arr[], write a function to search for a particular element x in the array. Linear Search finds the element in O(n) time, Jump Search takes O(n) time and Binary Search takes O(log n) time. The Interpolation Search is an improvement over Binary Se
15+ min read
Exponential Search
The name of this searching algorithm may be misleading as it works in O(Log n) time. The name comes from the way it searches an element. Given a sorted array, and an element x to be searched, find position of x in the array. Input: arr[] = {10, 20, 40, 45, 55} x = 45Output: Element found at index 3I
15+ min read
Fibonacci Search
Given a sorted array arr[] of size n and an element x to be searched in it. Return index of x if it is present in array else return -1. Examples: Input:  arr[] = {2, 3, 4, 10, 40}, x = 10Output: 3Element x is present at index 3. Input: arr[] = {2, 3, 4, 10, 40}, x = 11Output:  -1Element x is not
15+ min read
The Ubiquitous Binary Search | Set 1
We are aware of the binary search algorithm. Binary search is the easiest algorithm to get right. I present some interesting problems that I collected on binary search. There were some requests on binary search. I request you to honor the code, "I sincerely attempt to solve the problem and ensure th
15+ min read
Comparisons between Searching Algorithms
Library implementations of Searching algorithms
Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
In C++, STL provide various functions like std::binary_search(), std::lower_bound(), and std::upper_bound() which uses the the binary search algorithm for different purposes. These function will only work on the sorted data. There are the 3 binary search function in C++ STL: Table of Content binary_
3 min read
Arrays.binarySearch() in Java with Examples | Set 1
In Java, the Arrays.binarySearch() method searches the specified array of the given data type for the specified value using the binary search algorithm. The array must be sorted by the Arrays.sort() method before making this call. If it is not sorted, the results are undefined. Example: Below is a s
3 min read
Arrays.binarySearch() in Java with examples | Set 2 (Search in subarray)
Arrays.binarySearch()| Set 1 Covers how to find an element in a sorted array in Java. This set will cover "How to Search a key in an array within a given range including only start index". Syntax : public static int binarySearch(data_type[] arr, int fromIndex, int toIndex, data_type key) Parameters
5 min read
Collections.binarySearch() in Java with Examples
java.util.Collections.binarySearch() method is a java.util.Collections class method that returns the position of an object in a sorted list. // Returns index of key in a sorted list sorted in// ascending orderpublic static int binarySearch(List slist, T key)// Returns index of key in a sorted list s
4 min read
Easy problems on Searching algorithms
Find the Missing Number
Given an array arr[] of size n-1 with distinct integers in the range of [1, n]. This array represents a permutation of the integers from 1 to n with one element missing. Find the missing element in the array. Examples: Input: arr[] = [8, 2, 4, 5, 3, 7, 1]Output: 6Explanation: All the numbers from 1
12 min read
Find the first repeating element in an array of integers
Given an array of integers arr[], The task is to find the index of first repeating element in it i.e. the element that occurs more than once and whose index of the first occurrence is the smallest. Examples: Input: arr[] = {10, 5, 3, 4, 3, 5, 6}Output: 5 Explanation: 5 is the first element that repe
8 min read
Missing and Repeating in an Array
Given an unsorted array of size n. Array elements are in the range of 1 to n. One number from set {1, 2, ...n} is missing and one number occurs twice in the array. The task is to find these two numbers. Examples: Input: arr[] = {3, 1, 3}Output: 3, 2Explanation: In the array, 2 is missing and 3 occur
15+ min read
Count 1's in a sorted binary array
Given a binary array arr[] of size n, which is sorted in non-increasing order, count the number of 1's in it. Examples: Input: arr[] = [1, 1, 0, 0, 0, 0, 0]Output: 2Explanation: Count of the 1's in the given array is 2. Input: arr[] = [1, 1, 1, 1, 1, 1, 1]Output: 7 Input: arr[] = [0, 0, 0, 0, 0, 0,
8 min read
Two Sum - Pair Closest to 0
Given an integer array of N elements. You need to find the maximum sum of two elements such that sum is closest to zero. This problem is a variation of standard 2 Sum problems. Note: In Case if we have two of more ways to form sum of two elements closest to zero return the maximum sum.Example: Input
15 min read
Pair with the given difference
Given an unsorted array and an integer x, the task is to find if there exists a pair of elements in the array whose absolute difference is x. Examples: Input: arr[] = [5, 20, 3, 2, 50, 80], x = 78Output: YesExplanation: The pair is {2, 80}. Input: arr[] = [90, 70, 20, 80, 50], x = 45Output: NoExplan
14 min read
Kth smallest element in a row-wise and column-wise sorted 2D array
Given an n x n matrix, every row and column is sorted in non-decreasing order. Given a number K where K lies in the range [1, n*n], find the Kth smallest element in the given 2D matrix. Example: Input: mat ={{10, 20, 30, 40}, {15, 25, 35, 45}, {24, 29, 37, 48}, {32, 33, 39, 50 }}K = 3Output: 20Expla
15+ min read
Find common elements in three sorted arrays
Given three sorted arrays in non-decreasing order, print all common elements in non-decreasing order across these arrays. If there are no such elements return an empty array. In this case, the output will be -1. Note: In case of duplicate common elements, print only once. Examples: Input: arr1[] = [
12 min read
Ceiling in a sorted array
Given a sorted array and a value x, find index of the ceiling of x. The ceiling of x is the smallest element in an array greater than or equal to x. Note: In case of multiple occurrences of ceiling of x, return the index of the first occurrence. Examples : Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x
13 min read
Floor in a Sorted Array
Given a sorted array and a value x, find the element of the floor of x. The floor of x is the largest element in the array smaller than or equal to x. Examples: Input: arr[] = [1, 2, 8, 10, 10, 12, 19], x = 5Output: 1Explanation: Largest number less than or equal to 5 is 2, whose index is 1 Input: a
9 min read
Bitonic Point - Maximum in Increasing Decreasing Array
Given an array arr[] of integers which is initially strictly increasing and then strictly decreasing, the task is to find the bitonic point, that is the maximum value in the array. Bitonic Point is a point in bitonic sequence before which elements are strictly increasing and after which elements are
11 min read
Given Array of size n and a number k, find all elements that appear more than n/k times
Given an array of size n and an integer k, find all elements in the array that appear more than n/k times. Examples: Input: arr[ ] = [3, 4, 2, 2, 1, 2, 3, 3], k = 4Output: [2, 3]Explanation: Here n/k is 8/4 = 2, therefore 2 appears 3 times in the array that is greater than 2 and 3 appears 3 times in
15+ min read
Medium problems on Searching algorithms
3 Sum - Find All Triplets with Zero Sum
Given an array arr[], the task is to find all possible indices {i, j, k} of triplet {arr[i], arr[j], arr[k]} such that their sum is equal to zero and all indices in a triplet should be distinct (i != j, j != k, k != i). We need to return indices of a triplet in sorted order, i.e., i < j < k. E
11 min read
Find the element before which all the elements are smaller than it, and after which all are greater
Given an array, find an element before which all elements are equal or smaller than it, and after which all the elements are equal or greater. Note: Print -1, if no such element exists. Examples: Input: arr[] = [5, 1, 4, 3, 6, 8, 10, 7, 9]Output: 6 Explanation: 6 is present at index 4. All elements
14 min read
Largest pair sum in an array
Given an unsorted of distinct integers, find the largest pair sum in it. For example, the largest pair sum is 74. If there are less than 2 elements, then we need to return -1. Input : arr[] = {12, 34, 10, 6, 40}, Output : 74 Input : arr[] = {10, 10, 10}, Output : 20 Input arr[] = {10}, Output : -1 [
10 min read
Kâth Smallest Element in Unsorted Array
Given an array arr[] of N distinct elements and a number K, where K is smaller than the size of the array. Find the K'th smallest element in the given array. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content [Naive
15+ min read
Search in a Sorted and Rotated Array
Given a sorted and rotated array arr[] of n distinct elements, the task is to find the index of given key in the array. If the key is not present in the array, return -1. Examples: Input: arr[] = [5, 6, 7, 8, 9, 10, 1, 2, 3], key = 3Output: 8Explanation: 3 is present at index 8 in arr[]. Input: arr[
15+ min read
Minimum in a Sorted and Rotated Array
Given a sorted array of distinct elements arr[] of size n that is rotated at some unknown point, the task is to find the minimum element in it. Examples: Input: arr[] = [5, 6, 1, 2, 3, 4]Output: 1Explanation: 1 is the minimum element present in the array. Input: arr[] = [3, 1, 2]Output: 1Explanation
9 min read
Find a Fixed Point (Value equal to index) in a given array
Given an array of n distinct integers sorted in ascending order, the task is to find the First Fixed Point in the array. Fixed Point in an array is an index i such that arr[i] equals i. Note that integers in the array can be negative. Note: If no Fixed Point is present in the array, print -1. Exampl
7 min read
K Mmost Frequent Words in a File
Given a book of words and an integer K. Assume you have enough main memory to accommodate all words. Design a dynamic data structure to find the top K most frequent words in a book. The structure should allow new words to be added in main memory. Examples: Input: fileData = "Welcome to the world of
15+ min read
Find k closest elements to a given value
Given a sorted array arr[] and a value x, find the k closest elements to x in arr[]. Note that if the element is present in array, then it should not be in output, only the other closest elements are required. Examples: Input: k = 4, x = 35, arr[] = {12, 16, 22, 30, 35, 39, 42, 45, 48, 50, 53, 55, 5
15+ min read
2 Sum - Pair Sum Closest to Target using Binary Search
Given an array arr[] of n integers and an integer target, the task is to find a pair in arr[] such that itâs sum is closest to target. Note: Return the pair in sorted order and if there are multiple such pairs return the pair with maximum absolute difference. If no such pair exists return an empty a
10 min read
Find the closest pair from two sorted arrays
Given two arrays arr1[0...m-1] and arr2[0..n-1], and a number x, the task is to find the pair arr1[i] + arr2[j] such that absolute value of (arr1[i] + arr2[j] - x) is minimum. Example: Input: arr1[] = {1, 4, 5, 7}; arr2[] = {10, 20, 30, 40}; x = 32Output: 1 and 30Input: arr1[] = {1, 4, 5, 7}; arr2[]
15+ min read
Find three closest elements from given three sorted arrays
Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized. Here abs() indicates absolute value. Example : Input : A[] = {1, 4, 10} B[] = {2, 15, 20} C[] = {10, 12} Output: 10 15
15+ min read
Search in an Array of Rational Numbers without floating point arithmetic
Given a sorted array of rational numbers, where each rational number is represented in the form p/q (where p is the numerator and q is the denominator), the task is to find the index of a given rational number x in the array. If the number does not exist in the array, return -1. Examples: Input: arr
9 min read
Hard problems on Searching algorithms
Median of two sorted arrays of same size
Given 2 sorted arrays a[] and b[], each of size n, the task is to find the median of the array obtained after merging a[] and b[]. Note: Since the size of the merged array will always be even, the median will be the average of the middle two numbers. Input: a[] = [1, 12, 15, 26, 38], b[] = [2, 13, 1
15+ min read
Search in an almost sorted array
Given a sorted array arr[] of size n, some elements of array are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1] i.e. arr[i] can only be swapped with either arr[i+1] or arr[i-1]. The task is to search for an element in this array. Examples : Input: arr[
10 min read
Find position of an element in a sorted array of infinite numbers
Given a sorted array arr[] of infinite numbers. The task is to search for an element k in the array. Examples: Input: arr[] = [3, 5, 7, 9, 10, 90, 100, 130, 140, 160, 170], k = 10Output: 4Explanation: 10 is at index 4 in array. Input: arr[] = [2, 5, 7, 9], k = 3Output: -1Explanation: 3 is not presen
15+ min read
Pair Sum in a Sorted and Rotated Array
Given an array arr[] of size n, which is sorted and then rotated around an unknown pivot, the task is to check whether there exists a pair of elements in the array whose sum is equal to a given target value. Examples : Input: arr[] = [11, 15, 6, 8, 9, 10], target = 16Output: trueExplanation: There i
10 min read
Kâth Smallest/Largest Element in Unsorted Array | Worst case Linear Time
Given an array and a number k where k is smaller than the size of the array, we need to find the kâth smallest element in the given array. It is given that all array elements are distinct.Examples: Input: arr[] = {7, 10, 4, 3, 20, 15} k = 3Output: 7Input: arr[] = {7, 10, 4, 3, 20, 15} k = 4Output: 1
15+ min read
K'th largest element in a stream
Given an infinite stream of integers, find the Kth largest element at any point of time. Note: Here we have a stream instead of a whole array and we are allowed to store only K elements. Examples: Input: stream[] = {10, 20, 11, 70, 50, 40, 100, 5, . . .}, K = 3Output: {_, _, 10, 11, 20, 40, 50, 50,
14 min read
Best First Search (Informed Search)
Best First Search is a heuristic search algorithm that selects the most promising node for expansion based on an evaluation function. It prioritizes nodes in the search space using a heuristic to estimate their potential. By iteratively choosing the most promising node, it aims to efficiently naviga
13 min read