K-th Element of Merged Two Sorted Arrays
Last Updated :
03 Mar, 2025
Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays.
Examples:
Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5
Output: 6
Explanation: The final sorted array is [1, 2, 3, 4, 6, 7, 8, 9, 10]. The 5th element is 6.
Input: a[] = [100, 112, 256, 349, 770], b[] = [72, 86, 113, 119, 265, 445, 892], k = 7
Output: 256
Explanation: The final sorted array is [72, 86, 100, 112, 113, 119, 256, 265, 349, 445, 770, 892]. The 7th element is 256.
Using Sorting - O((m + n) * log(m + n)) Time and O(m + n) Space
The idea is to create a new array by merging elements from both arrays (a[]
and b[]
), then sort the new array, and finally return the kth smallest element from the sorted array.
C++
#include <bits/stdc++.h>
using namespace std;
int kthElement(vector<int> &a, vector<int> &b, int k) {
// to merge both the arrays
vector<int> arr;
// add the elements of array a
for(auto i: a)
arr.push_back(i);
// add the elements of array a
for(auto i: b)
arr.push_back(i);
// sort the merged array
sort(arr.begin(), arr.end());
// return the kth element
return arr[k-1];
}
int main() {
vector<int> a = {2, 3, 6, 7, 9};
vector<int> b = {1, 4, 8, 10};
int k = 5;
cout << kthElement(a, b, k);
return 0;
}
Java
// Function for finding kth element
import java.util.*;
class GfG {
// Function for finding kth element
static int kthElement(int[] a, int[] b, int k) {
// to merge both the arrays
ArrayList<Integer> arr = new ArrayList<>();
// add the elements of array a
for (int i : a)
arr.add(i);
// add the elements of array b
for (int i : b)
arr.add(i);
// sort the merged array
Collections.sort(arr);
// return the kth element
return arr.get(k - 1);
}
public static void main(String[] args) {
int[] a = {2, 3, 6, 7, 9};
int[] b = {1, 4, 8, 10};
int k = 5;
System.out.println(kthElement(a, b, k));
}
}
Python
# Function for finding kth element
def kthElement(a, b, k):
# to merge both the arrays
arr = []
# add the elements of array a
for i in a:
arr.append(i)
# add the elements of array b
for i in b:
arr.append(i)
# sort the merged array
arr.sort()
# return the kth element
return arr[k - 1]
if __name__ == "__main__":
a = [2, 3, 6, 7, 9]
b = [1, 4, 8, 10]
k = 5
print(kthElement(a, b, k))
C#
// Function for finding kth element
using System;
using System.Collections.Generic;
class GfG {
// Function for finding kth element
static int kthElement(int[] a, int[] b, int k) {
// to merge both the arrays
List<int> arr = new List<int>();
// add the elements of array a
foreach (int i in a)
arr.Add(i);
// add the elements of array b
foreach (int i in b)
arr.Add(i);
// sort the merged array
arr.Sort();
// return the kth element
return arr[k - 1];
}
static void Main() {
int[] a = {2, 3, 6, 7, 9};
int[] b = {1, 4, 8, 10};
int k = 5;
Console.WriteLine(kthElement(a, b, k));
}
}
JavaScript
// Function for finding kth element
function kthElement(a, b, k) {
// to merge both the arrays
let arr = [];
// add the elements of array a
for (let i of a)
arr.push(i);
// add the elements of array b
for (let i of b)
arr.push(i);
// sort the merged array
arr.sort((x, y) => x - y);
// return the kth element
return arr[k - 1];
}
let a = [2, 3, 6, 7, 9];
let b = [1, 4, 8, 10];
let k = 5;
console.log(kthElement(a, b, k));
Using Priority Queue - O((m + n + k) * log(m + n)) Time and O(m + n) Space
The idea is to build a min heap to store all the elements of both the arrays in sorted order, and then extract the first k elements to get the kth smallest element of the merge array.
C++
#include <bits/stdc++.h>
using namespace std;
int kthElement(vector<int> &a, vector<int> &b, int k) {
// to store the elements of both
// the arrays in sorted order
priority_queue<int, vector<int>, greater<int>> pq;
// add the elements of array a
for(auto i: a)
pq.push(i);
// add the elements of array a
for(auto i: b)
pq.push(i);
// pop the elements from the heap
// till k-1 elements are popped
while(k-- > 1)
pq.pop();
// return the kth element
return pq.top();
}
int main() {
vector<int> a = {2, 3, 6, 7, 9};
vector<int> b = {1, 4, 8, 10};
int k = 5;
cout << kthElement(a, b, k);
return 0;
}
Java
// Function for finding kth element
import java.util.*;
class GfG {
// Function for finding kth element
static int kthElement(int[] a, int[] b, int k) {
// to store the elements of both
// the arrays in sorted order
PriorityQueue<Integer> pq = new PriorityQueue<>();
// add the elements of array a
for (int i : a)
pq.add(i);
// add the elements of array a
for (int i : b)
pq.add(i);
// pop the elements from the heap
// till k-1 elements are popped
while (k-- > 1)
pq.poll();
// return the kth element
return pq.peek();
}
public static void main(String[] args) {
int[] a = {2, 3, 6, 7, 9};
int[] b = {1, 4, 8, 10};
int k = 5;
System.out.println(kthElement(a, b, k));
}
}
Python
# Function for finding kth element
import heapq
def kthElement(a, b, k):
# to store the elements of both
# the arrays in sorted order
pq = []
# add the elements of array a
for i in a:
heapq.heappush(pq, i)
# add the elements of array a
for i in b:
heapq.heappush(pq, i)
# pop the elements from the heap
# till k-1 elements are popped
while k > 1:
heapq.heappop(pq)
k -= 1
# return the kth element
return pq[0]
if __name__ == "__main__":
a = [2, 3, 6, 7, 9]
b = [1, 4, 8, 10]
k = 5
print(kthElement(a, b, k))
JavaScript
// Function for finding kth element
function kthElement(a, b, k) {
// to store the elements of both
// the arrays in sorted order
let pq = [];
// add the elements of array a
for (let i of a)
pq.push(i);
// add the elements of array a
for (let i of b)
pq.push(i);
// sort the merged array in ascending order
pq.sort((x, y) => x - y);
// pop the elements from the heap
// till k-1 elements are popped
while (k-- > 1)
pq.shift();
// return the kth element
return pq[0];
}
let a = [2, 3, 6, 7, 9];
let b = [1, 4, 8, 10];
let k = 5;
console.log(kthElement(a, b, k));
Using Merge Step of Merge Sort - O(m + n) Time and O(m + n) Space
The basic idea here is to merge the given two arrays into a single sorted array and then simply return the element at the kth position. This approach is straightforward because it directly uses the merging process of two sorted arrays, similar to the merge step in the merge sort algorithm.
Step-by-step approach:
- We initialize three pointers: two pointers to traverse each array and one to keep track of the position in the merged array.
- By comparing the elements pointed to by the two array pointers, we place the smaller element into the merged array and move the respective pointer forward.
- This continues until one of the arrays is fully traversed.
- If any elements remain in either array, they are directly appended to the merged array.
- Finally, the k-th element of this merged array is returned.
C++
// C++ program to find K-th Element of Merged Two Sorted Arrays
// Using merge step of merge sort
#include <bits/stdc++.h>
using namespace std;
int kthElement(vector<int> &a, vector<int> &b, int k) {
int n = a.size(), m = b.size();
// array to store the merged sorted array
vector<int> arr(n + m);
int i = 0, j = 0, d = 0;
while (i < n && j < m) {
// If the element of a[] is smaller, insert the
// element to the sorted array
if (a[i] < b[j])
arr[d++] = a[i++];
// If the element of b[] is smaller, insert the
// element to the sorted array
else
arr[d++] = b[j++];
}
// Push the remaining elements of a[]
while (i < n)
arr[d++] = a[i++];
// Push the remaining elements of b[]
while (j < m)
arr[d++] = b[j++];
return arr[k - 1];
}
int main() {
vector<int> a = {2, 3, 6, 7, 9};
vector<int> b = {1, 4, 8, 10};
int k = 5;
cout << kthElement(a, b, k);
return 0;
}
Java
// Java Program to find K-th Element of Merged Two Sorted Arrays
// Using merge step of merge sort
class GfG {
static int kthElement(int[] a, int[] b, int k) {
int n = a.length, m = b.length;
// array to store the merged sorted array
int[] arr = new int[n + m];
int i = 0, j = 0, d = 0;
while (i < n && j < m) {
// If the element of a[] is smaller, insert the
// element to the sorted array
if (a[i] < b[j]) {
arr[d++] = a[i++];
}
// If the element of b[] is smaller, insert the
// element to the sorted array
else {
arr[d++] = b[j++];
}
}
// Push the remaining elements of a[]
while (i < n) {
arr[d++] = a[i++];
}
// Push the remaining elements of b[]
while (j < m) {
arr[d++] = b[j++];
}
return arr[k - 1];
}
public static void main(String[] args) {
int[] a = {2, 3, 6, 7, 9};
int[] b = {1, 4, 8, 10};
int k = 5;
System.out.println(kthElement(a, b, k));
}
}
Python
# Python Program to find K-th Element of Merged Two Sorted Arrays
# Using merge step of merge sort
def kthElement(a, b, k):
n = len(a)
m = len(b)
# array to store the merged sorted array
arr = [0] * (n + m)
i = 0
j = 0
d = 0
while i < n and j < m:
# If the element of a[] is smaller, insert the
# element to the sorted array
if a[i] < b[j]:
arr[d] = a[i]
i += 1
# If the element of b[] is smaller, insert the
# element to the sorted array
else:
arr[d] = b[j]
j += 1
d += 1
# Push the remaining elements of a[]
while i < n:
arr[d] = a[i]
i += 1
d += 1
# Push the remaining elements of b[]
while j < m:
arr[d] = b[j]
j += 1
d += 1
return arr[k - 1]
if __name__ == "__main__":
arr1 = [2, 3, 6, 7, 9]
arr2 = [1, 4, 8, 10]
k = 5
print(kthElement(arr1, arr2, k))
C#
// C# program to find K-th Element of Merged Two Sorted Arrays
// Using merge step of merge sort
using System;
class GfG {
static int kthElement(int[] a, int[] b, int k) {
int n = a.Length, m = b.Length;
// array to store the merged sorted array
int[] arr = new int[n + m];
int i = 0, j = 0, d = 0;
while (i < n && j < m) {
// If the element of a[] is smaller, insert the
// element to the sorted array
if (a[i] < b[j])
arr[d++] = a[i++];
// If the element of b[] is smaller, insert the
// element to the sorted array
else
arr[d++] = b[j++];
}
// Push the remaining elements of a[]
while (i < n)
arr[d++] = a[i++];
// Push the remaining elements of b[]
while (j < m)
arr[d++] = b[j++];
return arr[k - 1];
}
static void Main() {
int[] a = { 2, 3, 6, 7, 9 };
int[] b = { 1, 4, 8, 10 };
int k = 5;
Console.WriteLine(kthElement(a, b, k));
}
}
JavaScript
// JavaScript program to find K-th Element of Merged Two Sorted Arrays
// Using merge step of merge sort
function kthElement(a, b, k) {
const n = a.length, m = b.length;
// array to store the merged sorted array
let arr = new Array(n + m);
let i = 0, j = 0, d = 0;
while (i < n && j < m) {
// If the element of a[] is smaller, insert the
// element to the sorted array
if (a[i] < b[j])
arr[d++] = a[i++];
// If the element of b[] is smaller, insert the
// element to the sorted array
else
arr[d++] = b[j++];
}
// Push the remaining elements of a[]
while (i < n)
arr[d++] = a[i++];
// Push the remaining elements of b[]
while (j < m)
arr[d++] = b[j++];
return arr[k - 1];
}
// Driver code
let a = [2, 3, 6, 7, 9];
let b = [1, 4, 8, 10];
let k = 5;
console.log(kthElement(a, b, k));
Using Optimized Merge of Merge Sort - O(k) Time and O(1) Space
This approach optimizes the space complexity of the above approach by avoiding the creation of an additional array. Instead, we use two pointers to traverse the input arrays and count the elements until we reach the kth element. This method is more efficient in terms of space since it only uses a constant amount of extra memory.
We start with two pointers at the beginning of each array and another counter to keep track of the number of elements processed. By comparing the current elements of both arrays, the smaller one is considered as part of the merged sequence, and the pointer for that array would be incremented by 1. This process continues until we have processed k elements. The kth element encountered in this process is the result.
C++
// C++ program to find K-th Element of Merged Two Sorted Arrays
// Using optimized merge step of merge sort
#include <bits/stdc++.h>
using namespace std;
int kthElement(vector<int> &a, vector<int> &b, int k) {
int n = a.size(), m = b.size();
// last element added to the merged sorted array
int last = 0;
int i = 0, j = 0;
for (int d = 0; d < k; ++d) {
if (i < n) {
// If a[i] > b[j] then increment j
if (j < m && a[i] > b[j]) {
last = b[j];
j++;
}
// Otherwise increment i
else {
last = a[i];
i++;
}
}
// If reached end of first array then increment j
else if (j < m) {
last = b[j];
j++;
}
}
// Return the last (kth) element
return last;
}
int main() {
vector<int> a = {2, 3, 6, 7, 9};
vector<int> b = {1, 4, 8, 10};
int k = 5;
cout << kthElement(a, b, k) << endl;
return 0;
}
Java
// Java program to find K-th Element of Merged Two Sorted Arrays
// Using optimized merge step of merge sort
class GfG {
static int kthElement(int[] a, int[] b, int k) {
int n = a.length, m = b.length;
// last element added to the merged sorted array
int last = 0;
int i = 0, j = 0;
for (int d = 0; d < k; ++d) {
if (i < n) {
// If a[i] > b[j] then increment j
if (j < m && a[i] > b[j]) {
last = b[j];
j++;
}
// otherwise increment i
else {
last = a[i];
i++;
}
}
// If reached end of first array then
// increment j
else if (j < m) {
last = b[j];
j++;
}
}
// return the last (kth) element
return last;
}
public static void main(String[] args) {
int[] a = {2, 3, 6, 7, 9};
int[] b = {1, 4, 8, 10};
int k = 5;
System.out.println(kthElement(a, b, k));
}
}
Python
# Python program to find K-th Element of Merged Two Sorted Arrays
# Using optimized merge step of merge sort
def kthElement(a, b, k):
n, m = len(a), len(b)
# last element added to the merged sorted array
last = 0
i, j = 0, 0
for _ in range(k):
if i < n:
# If a[i] > b[j] then increment j
if j < m and a[i] > b[j]:
last = b[j]
j += 1
# Otherwise increment i
else:
last = a[i]
i += 1
# If reached end of first array then increment j
elif j < m:
last = b[j]
j += 1
# Return the last (kth) element
return last
if __name__ == "__main__":
a = [2, 3, 6, 7, 9]
b = [1, 4, 8, 10]
k = 5
print(kthElement(a, b, k))
C#
// C# program to find K-th Element of Merged Two Sorted Arrays
// Using optimized merge step of merge sort
using System;
class GfG {
static int KthElement(int[] a, int[] b, int k) {
int n = a.Length, m = b.Length;
// last element added to the merged sorted array
int last = 0;
int i = 0, j = 0;
for (int d = 0; d < k; ++d) {
if (i < n) {
// If a[i] > b[j] then increment j
if (j < m && a[i] > b[j]) {
last = b[j];
j++;
}
// Otherwise increment i
else {
last = a[i];
i++;
}
}
// If reached end of first array then increment j
else if (j < m) {
last = b[j];
j++;
}
}
// Return the last (kth) element
return last;
}
public static void Main(string[] args) {
int[] a = { 2, 3, 6, 7, 9 };
int[] b = { 1, 4, 8, 10 };
int k = 5;
Console.WriteLine(KthElement(a, b, k));
}
}
JavaScript
// JavaScript program to find K-th Element of Merged Two Sorted Arrays
// Using optimized merge step of merge sort
function kthElement(a, b, k) {
const n = a.length, m = b.length;
// last element added to the merged sorted array
let last = 0;
let i = 0, j = 0;
for (let d = 0; d < k; ++d) {
if (i < n) {
// If a[i] > b[j] then increment j
if (j < m && a[i] > b[j]) {
last = b[j];
j++;
}
// Otherwise increment i
else {
last = a[i];
i++;
}
}
// If reached end of first array then increment j
else if (j < m) {
last = b[j];
j++;
}
}
// Return the last (kth) element
return last;
}
// Driver code
const a = [2, 3, 6, 7, 9];
const b = [1, 4, 8, 10];
const k = 5;
console.log(kthElement(a, b, k));
Using Binary Search - O(log(min(n, m)) Time and O(1) Space
The approach is similar to the Binary Search approach of Median of two sorted arrays of different sizes.
Consider the first array is smaller. If first array is greater, then swap the arrays to make sure that the first array is smaller.
- We mainly maintain two sets in this algorithm by doing binary search in the smaller array. Let mid1 be the partition of the smaller array. The first set contains elements from 0 to (mid1 – 1) from smaller array and mid2 = (k – mid1) elements from the greater array to make sure that the first set has exactly k elements. The second set contains remaining elements.
- Our target is to find a point in both arrays such that all elements in the first set are smaller than all elements in the other set (set that contains elements from right side). For this we validate the partitions using the same way as we did in Median of two sorted arrays of different sizes.
C++
// C++ program to find K-th Element of Merged Two Sorted Arrays
// using Binary Search
#include <bits/stdc++.h>
using namespace std;
int kthElement(vector<int> &a, vector<int> &b, int k) {
int n = a.size(), m = b.size();
// If a[] has more elements, then call kthElement
// with reversed parameters
if (n > m)
return kthElement(b, a, k);
// Binary Search on the number of elements we can
// include in the first set from a[]
int lo = max(0, k - m), hi = min(k, n);
while (lo <= hi) {
int mid1 = (lo + hi) / 2;
int mid2 = k - 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 == m ? INT_MAX : b[mid2]);
// If it is a valid partition
if (l1 <= r2 && l2 <= r1) {
// Find and return the maximum of l1 and l2
return max(l1, l2);
}
// Check if we need to take lesser elements from a[]
if (l1 > r2)
hi = mid1 - 1;
// Check if we need to take more elements from a[]
else
lo = mid1 + 1;
}
return 0;
}
int main() {
vector<int> a = {2, 3, 6, 7, 9};
vector<int> b = {1, 4, 8, 10};
int k = 5;
cout << kthElement(a, b, k);
return 0;
}
Java
// Java program to find K-th Element of Merged Two Sorted Arrays
// using Binary Search
import java.util.*;
class GfG {
static int kthElement(int[] a, int[] b, int k) {
int n = a.length, m = b.length;
// If a[] has more elements, then call kthElement
// with reversed parameters
if (n > m)
return kthElement(b, a, k);
// Binary Search on the number of elements we can
// include in the first set from a[]
int lo = Math.max(0, k - m), hi = Math.min(k, n);
while (lo <= hi) {
int mid1 = (lo + hi) / 2;
int mid2 = k - 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 a[]
int l2 = (mid2 == 0 ? Integer.MIN_VALUE :
b[mid2 - 1]);
int r2 = (mid2 == m ? Integer.MAX_VALUE :
b[mid2]);
// If it is a valid partition
if (l1 <= r2 && l2 <= r1) {
// Find and return the maximum of l1 and l2
return Math.max(l1, l2);
}
// Check if we need to take lesser elements from a[]
if (l1 > r2)
hi = mid1 - 1;
// Check if we need to take more elements from a[]
else
lo = mid1 + 1;
}
return 0;
}
public static void main(String[] args) {
int[] a = {2, 3, 6, 7, 9};
int[] b = {1, 4, 8, 10};
int k = 5;
System.out.println(kthElement(a, b, k));
}
}
Python
# Python program to find K-th Element of Merged Two Sorted Arrays
# using Binary Search
def kthElement(a, b, k):
n = len(a)
m = len(b)
# If a[] has more elements, then call kthElement
# with reversed parameters
if n > m:
return kthElement(b, a, k)
# Binary Search on the number of elements we can
# include in the first set from a[]
lo = max(0, k - m)
hi = min(k, n)
while lo <= hi:
mid1 = (lo + hi) // 2
mid2 = k - mid1
# Find elements to the left and right of partition in a[]
l1 = (mid1 == 0 and float('-inf') or a[mid1 - 1])
r1 = (mid1 == n and float('inf') or a[mid1])
# Find elements to the left and right of partition in b[]
l2 = (mid2 == 0 and float('-inf') or b[mid2 - 1])
r2 = (mid2 == m and float('inf') or b[mid2])
# If it is a valid partition
if l1 <= r2 and l2 <= r1:
# Find and return the maximum of l1 and l2
return max(l1, l2)
# Check if we need to take lesser elements from a[]
if l1 > r2:
hi = mid1 - 1
# Check if we need to take more elements from a[]
else:
lo = mid1 + 1
return 0
if __name__ == "__main__":
a = [2, 3, 6, 7, 9]
b = [1, 4, 8, 10]
k = 5
print(kthElement(a, b, k))
C#
// C# program to find K-th Element of Merged Two Sorted Arrays
// using Binary Search
using System;
class GfG {
static int kthElement(int[] a, int[] b, int k) {
int n = a.Length, m = b.Length;
// If a[] has more elements, then call kthElement
// with reversed parameters
if (n > m)
return kthElement(b, a, k);
// Binary Search on the number of elements we can
// include in the first set from a[]
int lo = Math.Max(0, k - m), hi = Math.Min(k, n);
while (lo <= hi) {
int mid1 = (lo + hi) / 2;
int mid2 = k - mid1;
// Find elements to the left and right of partition in a[]
int l1 = (mid1 == 0 ? Int32.MinValue : a[mid1 - 1]);
int r1 = (mid1 == n ? Int32.MaxValue : a[mid1]);
// Find elements to the left and right of partition in b[]
int l2 = (mid2 == 0 ? Int32.MinValue : b[mid2 - 1]);
int r2 = (mid2 == m ? Int32.MaxValue : b[mid2]);
// If it is a valid partition
if (l1 <= r2 && l2 <= r1) {
// Find and return the maximum of l1 and l2
return Math.Max(l1, l2);
}
// Check if we need to take lesser elements from a[]
if (l1 > r2)
hi = mid1 - 1;
// Check if we need to take more elements from a[]
else
lo = mid1 + 1;
}
return 0;
}
static void Main() {
int[] a = { 2, 3, 6, 7, 9 };
int[] b = { 1, 4, 8, 10 };
int k = 5;
Console.WriteLine(kthElement(a, b, k));
}
}
JavaScript
// JavaScript program to find K-th Element of Merged Two Sorted Arrays
// using Binary Search
function kthElement(a, b, k) {
let n = a.length, m = b.length;
// If a[] has more elements, then call kthElement
// with reversed parameters
if (n > m) {
return kthElement(b, a, k);
}
// Binary Search on the number of elements we can
// include in the first set from a[]
let lo = Math.max(0, k - m), hi = Math.min(k, n);
while (lo <= hi) {
let mid1 = Math.floor((lo + hi) / 2);
let mid2 = k - mid1;
// Find elements to the left and right of partition in a[]
let l1 = (mid1 === 0 ? -Infinity : a[mid1 - 1]);
let r1 = (mid1 === n ? Infinity : a[mid1]);
// Find elements to the left and right of partition in b[]
let l2 = (mid2 === 0 ? -Infinity : b[mid2 - 1]);
let r2 = (mid2 === m ? Infinity : b[mid2]);
// If it is a valid partition
if (l1 <= r2 && l2 <= r1) {
// Find and return the maximum of l1 and l2
return Math.max(l1, l2);
}
// Check if we need to take lesser elements from a[]
if (l1 > r2) {
hi = mid1 - 1;
}
// Check if we need to take more elements from a[]
else {
lo = mid1 + 1;
}
}
return 0;
}
// Driver Code
const a = [2, 3, 6, 7, 9];
const b = [1, 4, 8, 10];
const k = 5;
console.log(kthElement(a, b, k));
Similar Reads
Divide and Conquer Algorithm Divide and Conquer algorithm is a problem-solving strategy that involves. Divide : Break the given problem into smaller non-overlapping problems.Conquer : Solve Smaller ProblemsCombine : Use the Solutions of Smaller Problems to find the overall result.Examples of Divide and Conquer are Merge Sort, Q
1 min read
Introduction to Divide and Conquer Algorithm Divide and Conquer Algorithm is a problem-solving technique used to solve problems by dividing the main problem into subproblems, solving them individually and then merging them to find solution to the original problem. Divide and Conquer is mainly useful when we divide a problem into independent su
9 min read
Dynamic Programming vs Divide-and-Conquer In this article Iâm trying to explain the difference/similarities between dynamic programming and divide and conquer approaches based on two examples: binary search and minimum edit distance (Levenshtein distance).The ProblemWhen I started to learn algorithms it was hard for me to understand the mai
12 min read
Decrease and Conquer As divide-and-conquer approach is already discussed, which include following steps: Divide the problem into a number of subproblems that are smaller instances of the same problem. Conquer the sub problems by solving them recursively. If the subproblem sizes are small enough, however, just solve the
5 min read
Advanced master theorem for divide and conquer recurrences The Master Theorem is a tool used to solve recurrence relations that arise in the analysis of divide-and-conquer algorithms. The Master Theorem provides a systematic way of solving recurrence relations of the form: T(n) = aT(n/b) + f(n) where a, b, and f(n) are positive functions and n is the size o
5 min read
Some standard Divide and Conquer Algorithms
Write program to calculate pow(b, e)Given two numbers b and e, the task is to implement a function to compute b^e.Examples: Input: b = 3.00000, e = 5Output: 243.00000Input: b = 0.55000, e = 3Output: 0.16638Input: b = -0.67000, e = -7Output: -16.49971Table of Content[Naive Approach 1] Using Iteration - O(e) Time and O(1) Space[Naive Ap
10 min read
Karatsuba algorithm for fast multiplication using Divide and Conquer algorithmGiven two binary strings that represent value of two integers, find the product of two strings. For example, if the first bit string is "1100" and second bit string is "1010", output should be 120.For simplicity, let the length of two strings be same and be n.A Naive Approach is to follow the proces
15+ min read
Strassen's Matrix MultiplicationGiven two square matrices arr[][] and brr[][] of order n * n. Your task is to multiply both the matrices and find the resultant matrix.Examples:Input: arr[][] = [ [7, 8], [2, 9] ]brr[][] = [ [14, 5], [5, 18] ]Output: [ [138, 179], [73, 172] ]Input: arr[][] = [ [17, 4], [17, 16] ]brr[][] = [ [9, 2],
15+ min read
Convex Hull using Divide and Conquer AlgorithmIn computational geometry, a convex hull is the smallest convex polygon that contains a given set of points. It is a fundamental concept with applications in various fields such as computer graphics, robotics, and image processing. Importance of Convex Hull:Convex hulls are important in computationa
15 min read
Quickhull Algorithm for Convex HullGiven a set of points, a Convex hull is the smallest convex polygon containing all the given points. Input : points[] = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};Output : The points in convex hull are: (0, 0) (0, 3) (3, 1) (4, 4)Input : points[] = {{0, 3}, {1, 1}Output : Not P
14 min read
Binary Search based problems
Peak Element in ArrayGiven an array arr[] where no two adjacent elements are same, find the index of a peak element. An element is considered to be a peak element if it is strictly greater than its adjacent elements. If there are multiple peak elements, return the index of any one of them.Note: Consider the element befo
12 min read
Check for Majority Element in a sorted arrayGiven an array arr of N elements, A majority element in an array arr of size N is an element that appears more than N/2 times in the array. The task is to write a function say isMajority() that takes an array (arr[] ), arrayâs size (n) and a number to be searched (x) as parameters and returns true i
15+ min read
K-th Element of Merged Two Sorted ArraysGiven two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays.Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1,
15+ min read
Find the number of zeroesGiven an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.Examples : Input: arr[] = {1, 1, 1, 1, 0, 0} Output: 2 Input: arr[] = {1, 0, 0, 0, 0} Output: 4 Input: arr[] = {0, 0, 0} Output: 3 Input: arr[] = {1, 1, 1, 1} O
12 min read
Rotation Count in a Rotated Sorted arrayGiven an array arr[] having distinct numbers sorted in increasing order and the array has been right rotated (i.e, the last element will be cyclically shifted to the starting position of the array) k number of times, the task is to find the value of k.Examples: Input: arr[] = {15, 18, 2, 3, 6, 12}Ou
12 min read
Unbounded Binary Search Example (Find the point where a monotonically increasing function becomes positive first time)Given a function 'int f(unsigned int x)' which takes a non-negative integer 'x' as input and returns an integer as output. The function is monotonically increasing with respect to the value of x, i.e., the value of f(x+1) is greater than f(x) for every input x. Find the value 'n' where f() becomes p
11 min read
Median of two Sorted Arrays of Different SizesGiven two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array.This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal si
15+ min read
The Painter's Partition Problem using Binary SearchGiven an array arr[] and k, where the array represents the boards and each element of the given array represents the length of each board. k numbers of painters are available to paint these boards. Consider that each unit of a board takes 1 unit of time to paint.The task is to find the minimum time
10 min read
Some practice problems on Divide and Conquer algorithm
Program for Square Root of IntegerGiven a positive integer n, find its square root. If n is not a perfect square, then return floor of ân.Examples : Input: n = 4Output: 2Explanation: The square root of 4 is 2.Input: n = 11Output: 3Explanation: The square root of 11 lies in between 3 and 4 so floor of the square root is 3.Table of Co
11 min read
Maximum and minimum of an array using minimum number of comparisonsGiven an array of size N. The task is to find the maximum and the minimum element of the array using the minimum number of comparisons.Examples:Input: arr[] = {3, 5, 4, 1, 9}Output: Minimum element is: 1 Maximum element is: 9Input: arr[] = {22, 14, 8, 17, 35, 3}Output: Minimum element is: 3 Maximum
15+ min read
Find frequency of each element in a limited range array in less than O(n) timeGiven a sorted array arr[] of positive integers, the task is to find the frequency for each element in the array. Assume all elements in the array are less than some constant MNote: Do this without traversing the complete array. i.e. expected time complexity is less than O(n)Examples: Input: arr[] =
10 min read
Tiling Problem - L ShapedGiven an nÃn board (where n = 2k and kâ¥1), with one missing cell, the task is to fill the remaining cells using L-shaped tiles. An L-shaped tile covers 3 cells in a 2x2 grid, with one cell missing. You need to tile the entire board using the L-shaped tiles, ensuring that the missing cell remains unc
15+ min read
Count Inversions of an ArrayGiven an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j.Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorted
15+ min read
The Skyline Problem | Set-1Given n rectangular buildings in a 2-dimensional city, compute the skyline of these buildings, eliminating hidden lines. The main task is to view buildings from a side and remove all sections that are not visible. All buildings share a common bottom and every building is represented by a triplet (le
13 min read
Search in a Row-wise and Column-wise Sorted 2D Array using Divide and Conquer algorithmGiven an n x n matrix, where every row and column is sorted in increasing order. Given a key, how to decide whether this key is in the matrix. Input: x = 62, mat[][] = [[3, 30, 38], [20, 52, 54], [35, 60, 69]]Output: falseExplanation: 62 is not present in the matrix.Input: x = 30, mat[][] = [[3, 30]
7 min read
Allocate Minimum PagesGiven an array arr[] and an integer k, where arr[i] denotes the number of pages of a book and k denotes total number of students. All the books need to be allocated to k students in contiguous manner, with each student getting at least one book.The task is to minimize the maximum number of pages all
15+ min read