The Ubiquitous Binary Search | Set 1
Last Updated :
23 Jul, 2025
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 https://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 https://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 https://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 https://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
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching 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
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem