Median of two sorted arrays of same size
Last Updated :
02 Jan, 2025
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, 17, 30, 45]
Output: 16
Explanation: The merged sorted array is [1, 2, 12, 13, 15, 17, 26, 30, 38, 45]. The middle two elements are 15 and 17, so median = (15 + 17)/2 = 16
Input: a[] = [10], b[] = [21]
Output : 15.5
Explanation : The merged sorted array is [10, 21]. The middle two elements are 10 and 21, so median = (10 + 21)/2 = 15.5
[Naive Approach] Using Sorting - O(n * logn) Time and O(n) Space
The idea is to concatenate both the arrays into a new array, sort the new array and return the middle of the new sorted array.
Illustration:
a[] = [ 1, 12, 15, 26, 38 ], b[] = [ 2, 13, 17, 30, 45]
- After concatenating them in a third array : c[] = [ 1, 12, 15, 26, 38, 2, 13, 17, 30, 45]
- Sort c[] = [ 1, 2, 12, 13, 15, 17, 26, 30, 38, 45 ]
- So the median is the average of two middle elements: (15 + 17) / 2 = 16
C++
// C++ Code to find Median of two Sorted Arrays of
// Same Size using Sorting
#include <bits/stdc++.h>
using namespace std;
// Function to find the median of two sorted arrays of equal size
double getMedian(vector<int>& a, vector<int>& b) {
// Concatenate
vector<int> c(a.begin(), a.end());
c.insert(c.end(), b.begin(), b.end());
// Sort the concatenated array
sort(c.begin(), c.end());
// Calculate and return the median
int n = c.size();
int mid1 = n / 2;
int mid2 = mid1 - 1;
return (c[mid1] + c[mid2]) / 2.0;
}
int main() {
vector<int> a = { 1, 12, 15, 26, 38 };
vector<int> b = { 2, 13, 17, 30, 45 };
cout << getMedian(a, b) << endl;
return 0;
}
C
// C Code to find Median of two Sorted Arrays of
// Same Size using Sorting
#include <stdio.h>
// Function to compare two integers for qsort
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
// Function to find the median of two sorted arrays of equal size
double getMedian(int a[], int size1, int b[], int size2) {
// Concatenate arrays
int totalSize = size1 + size2;
int c[size1 + size2];
// Copy elements from a and b to c
for (int i = 0; i < size1; i++)
c[i] = a[i];
for (int i = 0; i < size2; i++)
c[size1 + i] = b[i];
// Sort the concatenated array
qsort(c, totalSize, sizeof(int), compare);
// Calculate and return the median
int mid1 = totalSize / 2;
int mid2 = mid1 - 1;
return (c[mid1] + c[mid2]) / 2.0;
}
int main() {
int a[] = { 1, 12, 15, 26, 38 };
int b[] = { 2, 13, 17, 30, 45 };
int size1 = sizeof(a) / sizeof(a[0]);
int size2 = sizeof(b) / sizeof(b[0]);
printf("%f", getMedian(a, size1, b, size2));
return 0;
}
Java
// Java Code to find Median of two Sorted Arrays of
// Same Size using Sorting
import java.util.Arrays;
class GfG {
// Function to find the median of two sorted arrays of equal size
static double getMedian(int[] a, int[] b) {
// Concatenate the two arrays
int[] c = new int[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
// Sort the concatenated array
Arrays.sort(c);
// Calculate and return the median
int n = c.length;
int mid1 = n / 2;
int mid2 = mid1 - 1;
return (c[mid1] + c[mid2]) / 2.0;
}
public static void main(String[] args) {
int[] a = { 1, 12, 15, 26, 38 };
int[] b = { 2, 13, 17, 30, 45 };
System.out.println(getMedian(a, b));
}
}
Python
# Python Code to find Median of two Sorted Arrays of
# Same Size using Sorting
# Function to find the median of two sorted arrays of
# equal size
def getMedian(a, b):
# Concatenate the two lists
c = a + b
# Sort the concatenated list
c.sort()
# Calculate and return the median
n = len(c)
mid1 = n // 2
mid2 = mid1 - 1
return (c[mid1] + c[mid2]) / 2.0
# Example usage
a = [1, 12, 15, 26, 38]
b = [2, 13, 17, 30, 45]
print(getMedian(a, b))
C#
// C# Code to find Median of two Sorted Arrays of
// Same Size using Sorting
using System;
using System.Linq;
class GfG {
// Function to find the median of two sorted arrays
// of equal size
static double getMedian(int[] a, int[] b) {
// Concatenate the two arrays
int[] c = a.Concat(b).ToArray();
// Sort the concatenated array
Array.Sort(c);
// Calculate and return the median
int n = c.Length;
int mid1 = n / 2;
int mid2 = mid1 - 1;
return (c[mid1] + c[mid2]) / 2.0;
}
static void Main() {
int[] a = { 1, 12, 15, 26, 38 };
int[] b = { 2, 13, 17, 30, 45 };
Console.WriteLine(getMedian(a, b));
}
}
JavaScript
// JavaScript Code to find Median of two Sorted Arrays of
// Same Size using Sorting
// Function to find the median of two sorted arrays of equal size
function getMedian(a, b) {
// Concatenate the two arrays
let c = a.concat(b);
// Sort the concatenated array
c.sort((a, b) => a - b);
// Calculate and return the median
let n = c.length;
let mid1 = Math.floor(n / 2);
let mid2 = mid1 - 1;
return (c[mid1] + c[mid2]) / 2;
}
// Example usage
let a = [1, 12, 15, 26, 38];
let b = [2, 13, 17, 30, 45];
console.log(getMedian(a, b));
Time Complexity: O((2n) * log(2n)), where n is the size of array a[] and b[].
Auxiliary Space: O(2n), because we are creating a new merged array of size 2n.
[Better Approach] Using Merge of Merge Sort - O(n) Time and O(1) Space
The given arrays are sorted, so merge the sorted arrays in an efficient way and keep the count of elements processed so far. So when we reach half of the total, print the median. The median will be the average of elements at index (n - 1) and n in the array obtained after merging both the arrays.
C++
// C++ Code to find Median of two Sorted Arrays of
// Same Size using Merge of Merge Sort
#include <bits/stdc++.h>
using namespace std;
// Function to find the median of two sorted arrays
// of equal size
float getMedian(vector<int>& a, vector<int>& b) {
int n = a.size();
int i = 0, j = 0;
int count;
// m1 to store element at index n of merged array
// m2 to store element at index (n - 1) of merged array
int m1 = -1, m2 = -1;
// Loop till n
for (count = 0; count <= n; count++) {
m2 = m1;
// If both the arrays have remaining elements
if (i < n && j < n) {
if (a[i] > b[j])
m1 = b[j++];
else
m1 = a[i++];
}
// If only a has remaining elements
else if (i < n)
m1 = a[i++];
// If only b has remaining elements
else
m1 = b[j++];
}
return (m1 + m2) / 2.0;
}
int main() {
vector<int> a = { 1, 12, 15, 26, 38 };
vector<int> b = { 2, 13, 17, 30, 45 };
cout << getMedian(a, b) << endl;
return 0;
}
C
// C Code to find Median of two Sorted Arrays of
// Same Size using Merge of Merge Sort
#include <stdio.h>
// Function to find the median of two sorted arrays of equal size
float getMedian(int a[], int b[], int n) {
int i = 0, j = 0;
int count;
int m1 = -1, m2 = -1;
// Loop till n
for (count = 0; count <= n; count++) {
m2 = m1;
// If both the arrays have remaining elements
if (i < n && j < n) {
if (a[i] > b[j])
m1 = b[j++];
else
m1 = a[i++];
}
// If only a has remaining elements
else if (i < n)
m1 = a[i++];
// If only b has remaining elements
else
m1 = b[j++];
}
return (m1 + m2) / 2.0;
}
int main() {
int a[] = { 1, 12, 15, 26, 38 };
int b[] = { 2, 13, 17, 30, 45 };
int n = sizeof(a) / sizeof(a[0]);
printf("%f", getMedian(a, b, n));
return 0;
}
Java
// Java Code to find Median of two Sorted Arrays of
// Same Size using Merge of Merge Sort
import java.util.Arrays;
class GfG {
// Function to find the median of two sorted arrays of equal size
static double getMedian(int[] a, int[] b) {
int n = a.length;
int i = 0, j = 0;
int count;
// m1 to store element at index n of merged array
// m2 to store element at index (n - 1) of merged array
int m1 = -1, m2 = -1;
// Loop till n
for (count = 0; count <= n; count++) {
m2 = m1;
// If both the arrays have remaining elements
if (i < n && j < n) {
if (a[i] > b[j])
m1 = b[j++];
else
m1 = a[i++];
}
// If only a has remaining elements
else if (i < n)
m1 = a[i++];
// If only b has remaining elements
else
m1 = b[j++];
}
return (m1 + m2) / 2.0;
}
public static void main(String[] args) {
int[] a = { 1, 12, 15, 26, 38 };
int[] b = { 2, 13, 17, 30, 45 };
System.out.println(getMedian(a, b));
}
}
Python
# Python Code to find Median of two Sorted Arrays of
# Same Size using Merge of Merge Sort
# Function to find the median of two sorted arrays
# of equal size
def getMedian(a, b):
n = len(a)
i, j = 0, 0
count = 0
# m1 to store element at index n of merged array
# m2 to store element at index (n - 1) of merged array
m1, m2 = -1, -1
# Loop till n
for count in range(n + 1):
m2 = m1
# If both the arrays have remaining elements
if i < n and j < n:
if a[i] > b[j]:
m1 = b[j]
j += 1
else:
m1 = a[i]
i += 1
# If only a has remaining elements
elif i < n:
m1 = a[i]
i += 1
# If only b has remaining elements
else:
m1 = b[j]
j += 1
return (m1 + m2) / 2.0
a = [1, 12, 15, 26, 38]
b = [2, 13, 17, 30, 45]
print(getMedian(a, b))
C#
// C# Code to find Median of two Sorted Arrays of
// Same Size using Merge of Merge Sort
using System;
using System.Linq;
class GfG {
// Function to find the median of two sorted arrays
// of equal size
static float getMedian(int[] a, int[] b) {
int n = a.Length;
int i = 0, j = 0;
int count;
// m1 to store element at index n of merged array
// m2 to store element at index (n - 1) of merged array
int m1 = -1, m2 = -1;
// Loop till n
for (count = 0; count <= n; count++) {
m2 = m1;
// If both the arrays have remaining elements
if (i < n && j < n) {
if (a[i] > b[j])
m1 = b[j++];
else
m1 = a[i++];
}
// If only a has remaining elements
else if (i < n)
m1 = a[i++];
// If only b has remaining elements
else
m1 = b[j++];
}
return (m1 + m2) / 2.0f;
}
static void Main() {
int[] a = { 1, 12, 15, 26, 38 };
int[] b = { 2, 13, 17, 30, 45 };
Console.WriteLine(getMedian(a, b));
}
}
JavaScript
// JavaScript Code to find Median of two Sorted Arrays of
// Same Size using Merge of Merge Sort
// Function to find the median of two sorted arrays
// of equal size
function getMedian(a, b) {
let n = a.length;
let i = 0, j = 0;
let count;
// m1 to store element at index n of merged array
// m2 to store element at index (n - 1) of merged array
let m1 = -1, m2 = -1;
// Loop till n
for (count = 0; count <= n; count++) {
m2 = m1;
// If both the arrays have remaining elements
if (i < n && j < n) {
if (a[i] > b[j])
m1 = b[j++];
else
m1 = a[i++];
}
// If only a has remaining elements
else if (i < n)
m1 = a[i++];
// If only b has remaining elements
else
m1 = b[j++];
}
return (m1 + m2) / 2.0;
}
let a = [ 1, 12, 15, 26, 38 ];
let b = [2, 13, 17, 30, 45 ];
console.log(getMedian(a, b));
Time Complexity: O(n), where n is the size of array a[] and b[].
Auxiliary Space: O(1)
[Expected Approach] Using Binary Search - O(log n) Time and O(1) Space
To find the median of the two sorted arrays, a[] and b[] of size n, we need the average of two middle elements of merged sorted array. So, if we divide the merged array into two halves, then the median will be (last element in first half + first element in second half) / 2.
The idea is to use Binary Search to find the valid partition in a[] say mid1, such that all elements of a[0...mid1 - 1] will lie in the first half of the merged sorted array. Since, we know that first half of the merged sorted array will have total n elements, the remaining mid2 = (n - mid1) elements will be from b[]. In other words, the first half of the merged sorted array will have all the elements in a[0...mid1 - 1] and b[0...mid2 - 1].
How to check if the partition mid1 and mid2 is valid or not?
For mid1 and mid2 to be valid, we need to check for the following conditions:
- All elements in a[0...mid1 - 1] should be less than or equal to all elements in b[mid2...n - 1]. Since both the subarrays are sorted individually, we can check a[mid1 - 1] should be less than or equal to b[mid2].
- All elements in b[0...mid2 - 1] should be less than or equal to all elements in a[mid1...n - 1]. Since both the subarrays are sorted individually, we can check b[mid2 - 1] should be less than or equal to a[mid1].
For simplicity, take the element to the left of partition mid1 as l1, so l1 = a[mid1 - 1] and element to the right of partition mid1 as r1, so r1 = a[mid1]. Similarly, take the element to the left of mid2 as l2, so l2 = b[mid1 - 1] and element to the right of mid2 as r2, so r2 = b[mid2]. So, the above conditions can be simplified as l1 <= r2 and l2 <= r1.
If the partition is not valid, we can have two cases:
- If l1 > r2, this means that we have taken extra elements from a[], so take less elements by moving high = mid - 1.
- If l2 > r1, this means that we have taken less elements from a[], so take more elements by moving low = mid + 1.
Illustration:
Below is the implementation of the above approach:
C++
// C++ Program to find the median of merged sorted
// array using Binary Search
#include <bits/stdc++.h>
using namespace std;
// function to find median of merged sorted array
double getMedian(vector<int> &a, vector<int> &b) {
int n = a.size();
// We can take [0...n] number of elements from a[]
int low = 0, high = n;
while(low <= high) {
// Take mid1 elements from a
int mid1 = (low + high) / 2;
// Take mid2 elements from b
int mid2 = n - mid1;
// Find elements to the left and right of partition in a
int l1 = (mid1 == 0 ? INT_MIN : a[mid1 - 1]);
int r1 = (mid1 == n ? INT_MAX : a[mid1]);
// Find elements to the left and right of partition in b
int l2 = (mid2 == 0 ? INT_MIN : b[mid2 - 1]);
int r2 = (mid2 == n ? INT_MAX : b[mid2]);
// If it is a valid partition
if(l1 <= r2 && l2 <= r1)
return (max(l1, l2) + min(r1, r2)) / 2.0;
// If we need to take lesser elements from a
if(l1 > r2)
high = mid1 - 1;
// If we need to take more elements from a
else
low = mid1 + 1;
}
return 0;
}
int main() {
vector<int> a = { 1, 12, 15, 26, 38 };
vector<int> b = { 2, 13, 17, 30, 45 };
cout << getMedian(a, b) << endl;
return 0;
}
C
// C Program to find the median of merged sorted
// array using Binary Search
#include <stdio.h>
#include <limits.h>
// Function to find median of merged sorted array
double getMedian(int a[], int b[], int n) {
int low = 0, high = n;
while (low <= high) {
// Take mid1 elements from a
int mid1 = (low + high) / 2;
// Take mid2 elements from b
int mid2 = n - mid1;
// Find elements to the left and right of partition in a
int l1 = (mid1 == 0 ? INT_MIN : a[mid1 - 1]);
int r1 = (mid1 == n ? INT_MAX : a[mid1]);
// Find elements to the left and right of partition in b
int l2 = (mid2 == 0 ? INT_MIN : b[mid2 - 1]);
int r2 = (mid2 == n ? INT_MAX : b[mid2]);
// If it is a valid partition
if (l1 <= r2 && l2 <= r1)
return (fmax(l1, l2) + fmin(r1, r2)) / 2.0;
// If we need to take fewer elements from a
if (l1 > r2)
high = mid1 - 1;
// If we need to take more elements from a
else
low = mid1 + 1;
}
return 0.0;
}
int main() {
int a[] = {1, 12, 15, 26, 38};
int b[] = {2, 13, 17, 30, 45};
int n = sizeof(a) / sizeof(a[0]);
printf("%f", getMedian(a, b, n));
return 0;
}
Java
// Java Program to find the median of merged sorted
// array using Binary Search
import java.util.Arrays;
class GfG {
// Function to find median of merged sorted array
static double getMedian(int[] a, int[] b) {
int n = a.length;
// We can take [0...n] number of elements from a[]
int low = 0, high = n;
while (low <= high) {
// Take mid1 elements from a
int mid1 = (low + high) / 2;
// Take mid2 elements from b
int mid2 = n - mid1;
// Find elements to the left and right of partition in a
int l1 = (mid1 == 0 ? Integer.MIN_VALUE : a[mid1 - 1]);
int r1 = (mid1 == n ? Integer.MAX_VALUE : a[mid1]);
// Find elements to the left and right of partition in b
int l2 = (mid2 == 0 ? Integer.MIN_VALUE : b[mid2 - 1]);
int r2 = (mid2 == n ? Integer.MAX_VALUE : b[mid2]);
// If it is a valid partition
if (l1 <= r2 && l2 <= r1)
return (Math.max(l1, l2) + Math.min(r1, r2)) / 2.0;
// If we need to take fewer elements from a
if (l1 > r2)
high = mid1 - 1;
// If we need to take more elements from a
else
low = mid1 + 1;
}
return 0;
}
public static void main(String[] args) {
int[] a = {1, 12, 15, 26, 38};
int[] b = {2, 13, 17, 30, 45};
System.out.println(getMedian(a, b));
}
}
Python
# Python Program to find the median of merged sorted
# array using Binary Search
# Function to find median of merged sorted array
def getMedian(a, b):
n = len(a)
# We can take [0...n] number of elements from a[]
low, high = 0, n
while low <= high:
# Take mid1 elements from a
mid1 = (low + high) // 2
# Take mid2 elements from b
mid2 = n - mid1
# Find elements to the left and right of partition in a
l1 = float('-inf') if mid1 == 0 else a[mid1 - 1]
r1 = float('inf') if mid1 == n else a[mid1]
# Find elements to the left and right of partition in b
l2 = float('-inf') if mid2 == 0 else b[mid2 - 1]
r2 = float('inf') if mid2 == n else b[mid2]
# If it is a valid partition
if l1 <= r2 and l2 <= r1:
return (max(l1, l2) + min(r1, r2)) / 2.0
# If we need to take fewer elements from a
if l1 > r2:
high = mid1 - 1
# If we need to take more elements from a
else:
low = mid1 + 1
return 0
a = [1, 12, 15, 26, 38]
b = [2, 13, 17, 30, 45]
print(getMedian(a, b))
C#
// C# Program to find the median of merged sorted
// array using Binary Search
using System;
class GfG {
// Function to find median of merged sorted array
static double getMedian(int[] a, int[] b) {
int n = a.Length;
// We can take [0...n] number of elements from a[]
int low = 0, high = n;
while (low <= high) {
// Take mid1 elements from a
int mid1 = (low + high) / 2;
// Take mid2 elements from b
int mid2 = n - mid1;
// Find elements to the left and right of partition in a
int l1 = (mid1 == 0) ? int.MinValue : a[mid1 - 1];
int r1 = (mid1 == n) ? int.MaxValue : a[mid1];
// Find elements to the left and right of partition in b
int l2 = (mid2 == 0) ? int.MinValue : b[mid2 - 1];
int r2 = (mid2 == n) ? int.MaxValue : b[mid2];
// If it is a valid partition
if (l1 <= r2 && l2 <= r1)
return (Math.Max(l1, l2) + Math.Min(r1, r2)) / 2.0;
// If we need to take fewer elements from a
if (l1 > r2)
high = mid1 - 1;
// If we need to take more elements from a
else
low = mid1 + 1;
}
return 0;
}
static void Main() {
int[] a = { 1, 12, 15, 26, 38 };
int[] b = { 2, 13, 17, 30, 45 };
Console.WriteLine(getMedian(a, b));
}
}
JavaScript
// JavaScript Program to find the median of merged sorted
// array using Binary Search
// Function to find median of merged sorted array
function getMedian(a, b) {
const n = a.length;
let low = 0, high = n;
while (low <= high) {
// Take mid1 elements from a
const mid1 = Math.floor((low + high) / 2);
// Take mid2 elements from b
const mid2 = n - mid1;
// Find elements to the left and right of partition in a
const l1 = (mid1 === 0) ? -Infinity : a[mid1 - 1];
const r1 = (mid1 === n) ? Infinity : a[mid1];
// Find elements to the left and right of partition in b
const l2 = (mid2 === 0) ? -Infinity : b[mid2 - 1];
const r2 = (mid2 === n) ? Infinity : b[mid2];
// If it is a valid partition
if (l1 <= r2 && l2 <= r1) {
return (Math.max(l1, l2) + Math.min(r1, r2)) / 2.0;
}
// If we need to take fewer elements from a
if (l1 > r2) {
high = mid1 - 1;
}
// If we need to take more elements from a
else {
low = mid1 + 1;
}
}
// Return 0 if no median found (this should not happen with valid input)
return 0;
}
// Example usage
const a = [1, 12, 15, 26, 38];
const b = [2, 13, 17, 30, 45];
console.log(getMedian(a, b));
Time Complexity: O(log n), where n is the size of input array.
Auxiliary Space: O(1)
Related Articles:
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 AlgorithmGiven 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 ImplementationBinary 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). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Other Searching Algorithms
Sentinel Linear SearchSentinel 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 SearchMeta 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 SearchComputer 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 SearchLike 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 SearchGiven 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 SearchThe 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 3Inp
15+ min read
Fibonacci SearchGiven a sorted array arr[] of size n and an integer x. Your task is to check if the integer x is present in the array arr[] or not. Return index of x if it is present in array else return -1. Examples: Input: arr[] = [2, 3, 4, 10, 40], x = 10Output: 3Explanation: 10 is present at index 3.Input: arr[
11 min read
The Ubiquitous Binary Search | Set 1We 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 Contentbinary_sea
3 min read
Arrays.binarySearch() in Java with Examples | Set 1In 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 si
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 Examplesjava.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 so
4 min read
Easy problems on Searching algorithms
Find the Missing NumberGiven 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 t
12 min read
Find the first repeating element in an array of integersGiven 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 ArrayGiven 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 occurs
15+ min read
Count 1's in a sorted binary arrayGiven 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: 7Input: arr[] = [0, 0, 0, 0, 0, 0, 0]
7 min read
Two Sum - Pair Closest to 0Given an integer array arr[], the task is to find the maximum sum of two elements such that sum is closest to zero. Note: In case if we have two of more ways to form sum of two elements closest to zero return the maximum sum.Examples:Input: arr[] = [-8, 5, 2, -6]Output: -1Explanation: The min absolu
15+ min read
Pair with the given differenceGiven 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: NoExplana
14 min read
Kth smallest element in a row-wise and column-wise sorted 2D arrayGiven 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: 20Explanat
15+ min read
Find common elements in three sorted arraysGiven 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[] = [1,
12 min read
Ceiling in a sorted arrayGiven 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 ArrayGiven 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 1Input: arr[
9 min read
Bitonic Point - Maximum in Increasing Decreasing ArrayGiven 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. Note: Bitonic Point is a point in bitonic sequence before which elements are strictly increasing and after which elemen
10 min read
Given Array of size n and a number k, find all elements that appear more than n/k timesGiven 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 SumGiven 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.Ex
11 min read
Find the element before which all the elements are smaller than it, and after which all are greaterGiven 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 on
14 min read
Largest pair sum in an arrayGiven 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 : 74Input : arr[] = {10, 10, 10}, Output : 20Input arr[] = {10}, Output : -1[Naiv
10 min read
Kâth Smallest Element in Unsorted ArrayGiven 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: 7Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 4 Output: 10 Table of Content[Naive Ap
15 min read
Search in a Sorted and Rotated ArrayGiven 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 ArrayGiven 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 arrayGiven 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.Example
7 min read
K Mmost Frequent Words in a FileGiven 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 Ge
15+ min read
Closest K Elements in a Sorted ArrayYou are given a sorted array arr[] containing unique integers, a number k, and a target value x. Your goal is to return exactly k elements from the array that are closest to x, excluding x itself if it is present in the array.An element a is closer to x than b if:|a - x| < |b - x|, or|a - x| == |
15+ min read
2 Sum - Pair Sum Closest to Target using Binary SearchGiven 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 ar
10 min read
Find the closest pair from two sorted arraysGiven 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 arraysGiven 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 arithmeticGiven 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 sizeGiven 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, 17
15+ min read
Search in an almost sorted arrayGiven a sorted integer array arr[] consisting of distinct elements, where some elements of the array are moved to either of the adjacent positions, i.e. arr[i] may be present at arr[i-1] or arr[i+1].Given an integer target. You have to return the index ( 0-based ) of the target in the array. If targ
7 min read
Find position of an element in a sorted array of infinite numbersGiven 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 present i
15+ min read
Pair Sum in a Sorted and Rotated ArrayGiven 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 is
10 min read
Kâth Smallest/Largest Element in Unsorted Array | Worst case Linear TimeGiven an array of distinct integers arr[] and an integer k. The task is to find the k-th smallest element in the array. For better understanding, k refers to the element that would appear in the k-th position if the array were sorted in ascending order. Note: k will always be less than the size of t
15 min read
K'th largest element in a streamGiven an input stream of n integers, represented as an array arr[], and an integer k. After each insertion of an element into the stream, you need to determine the kth largest element so far (considering all elements including duplicates). If k elements have not yet been inserted, return -1 for that
15+ 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