Merge two sorted arrays in constant space using Min Heap
Last Updated :
12 Jul, 2025
Given two sorted arrays, we need to merge them with O(1) extra space into a sorted array, when N is the size of the first array, and M is the size of the second array.
Example
:
Input: arr1[] = {10};
arr2[] = {2, 3};
Output: arr1[] = {2}
arr2[] = {3, 10}
Input: arr1[] = {1, 5, 9, 10, 15, 20};
arr2[] = {2, 3, 8, 13};
Output: arr1[] = {1, 2, 3, 5, 8, 9}
arr2[] = {10, 13, 15, 20}
We had already discussed two more approaches to solve the above problem in constant space:
In this article, one more approach using the concept of the heap data structure is discussed without taking any extra space to merge the two sorted arrays. Below is the detailed approach in steps:
- The idea is to convert the second array into a min-heap first. This can be done in O(M) time complexity.
- After converting the second array to min-heap:
- Start traversing the first array and compare the current element for the first array to top of the created min_heap.
- If the current element in the first array is greater than heap top, swap the current element of the first array with the root of the heap, and heapify the root of the min_heap.
- After performing the above operation for every element of the first array, the first array will now contain first N elements of the sorted merged array.
- Now, the elements remained in the min_heap or the second array are the last M elements of the sorted merged array.
- To arrange them in sorted order, apply in-place heapsort on the second array.
Note
: We have used built-in STL functions available in C++ to convert array to min_heap, sorting the heap etc. It is recommended to read -
Heap in C++ STL | make_heap(), push_heap(), pop_heap(), sort_heap() before moving on to the program. Below is the implementation of the above approach:
CPP14
// C++ program to merge two sorted arrays in
// constant space
#include <bits/stdc++.h>
using namespace std;
// Function to merge two sorted arrays in
// constant space
void mergeArrays(int* a, int n, int* b, int m)
{
// Convert second array into a min_heap
// using make_heap() STL function [takes O(m)]
make_heap(b, b + m, greater<int>());
// Start traversing the first array
for (int i = 0; i < n; i++) {
// If current element is greater than root
// of min_heap
if (a[i] > b[0]) {
// Pop minimum element from min_heap using
// pop_heap() STL function
// The pop_heap() function removes the minimum element from
// heap and moves it to the end of the container
// converted to heap and reduces heap size by 1
pop_heap(b, b + m, greater<int>());
// Swapping the elements
int tmp = a[i];
a[i] = b[m - 1];
b[m - 1] = tmp;
// Apply push_heap() function on the container
// or array to again reorder it in the
// form of min_heap
push_heap(b, b + m, greater<int>());
}
}
// Convert the second array again into max_heap
// because sort_heap() on min heap sorts the array
// in decreasing order
// This step is [O(m)]
make_heap(b, b + m); // It's a max_heap
// Sort the second array using sort_heap() function
sort_heap(b, b + m);
}
// Driver Code
int main()
{
int ar1[] = { 1, 5, 9, 10, 15, 20 };
int ar2[] = { 2, 3, 8, 13 };
int m = sizeof(ar1) / sizeof(ar1[0]);
int n = sizeof(ar2) / sizeof(ar2[0]);
mergeArrays(ar1, m, ar2, n);
cout << "After Merging :- \nFirst Array: ";
for (int i = 0; i < m; i++)
cout << ar1[i] << " ";
cout << "\nSecond Array: ";
for (int i = 0; i < n; i++)
cout << ar2[i] << " ";
return 0;
}
Java
// Nikunj Sonigara
import java.util.*;
public class Main {
// Function to merge two sorted arrays in constant space
public static void mergeArrays(int[] a, int n, int[] b, int m) {
// Convert the second array into a min heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int value : b) {
minHeap.offer(value);
}
// Start traversing the first array
for (int i = 0; i < n; i++) {
// If the current element is greater than the root of the min heap
if (a[i] > minHeap.peek()) {
// Remove and retrieve the minimum element from the min heap
int min = minHeap.poll();
// Swap the elements
int tmp = a[i];
a[i] = min;
minHeap.offer(tmp);
}
}
// Convert the min heap (second array) back to an array
int index = 0;
while (!minHeap.isEmpty()) {
b[index++] = minHeap.poll();
}
// Sort the second array
Arrays.sort(b);
}
// Driver Code
public static void main(String[] args) {
int[] ar1 = { 1, 5, 9, 10, 15, 20 };
int[] ar2 = { 2, 3, 8, 13 };
int m = ar1.length;
int n = ar2.length;
mergeArrays(ar1, m, ar2, n);
System.out.println("After Merging :- \nFirst Array: " + Arrays.toString(ar1));
System.out.println("Second Array: " + Arrays.toString(ar2));
}
}
Python
# Nikunj Sonigara
import heapq
# Function to merge two sorted arrays in constant space
def mergeArrays(a, n, b, m):
# Convert the second array into a min heap
heapq.heapify(b)
# Start traversing the first array
for i in range(n):
# If the current element is greater than the root of the min heap
if a[i] > b[0]:
# Pop the minimum element from the min heap
min_val = heapq.heappop(b)
# Swap the elements
a[i], min_val = min_val, a[i]
# Push the swapped value back to the min heap
heapq.heappush(b, min_val)
# Sort the second array
heapq.heapify(b) # Convert the min heap back to a heap
b.sort()
# Driver Code
if __name__ == "__main__":
ar1 = [1, 5, 9, 10, 15, 20]
ar2 = [2, 3, 8, 13]
m = len(ar1)
n = len(ar2)
mergeArrays(ar1, m, ar2, n)
print("After Merging :- \nFirst Array: ", ar1)
print("Second Array: ", ar2)
C#
using System;
using System.Collections.Generic;
class MainClass
{
// Function to merge two sorted arrays in constant space
public static void MergeArrays(int[] a, int n, int[] b, int m)
{
// Convert the second array into a SortedSet
SortedSet<int> minHeap = new SortedSet<int>(b);
// Start traversing the first array
for (int i = 0; i < n; i++)
{
// If the current element is greater than the first element in the SortedSet
if (a[i] > minHeap.Min)
{
// Remove and retrieve the minimum element from the SortedSet
int min = minHeap.Min;
minHeap.Remove(min);
// Swap the elements
int tmp = a[i];
a[i] = min;
minHeap.Add(tmp);
}
}
// Convert the SortedSet (second array) back to an array
int index = 0;
foreach (var element in minHeap)
{
b[index++] = element;
}
// Sort the second array
Array.Sort(b);
}
// Driver Code
public static void Main(string[] args)
{
int[] ar1 = { 1, 5, 9, 10, 15, 20 };
int[] ar2 = { 2, 3, 8, 13 };
int m = ar1.Length;
int n = ar2.Length;
MergeArrays(ar1, m, ar2, n);
Console.WriteLine("After Merging :- \nFirst Array: " + string.Join(", ", ar1));
Console.WriteLine("Second Array: " + string.Join(", ", ar2));
}
}
JavaScript
class PriorityQueue {
constructor() {
this.heap = [];
}
offer(value) {
this.heap.push(value);
this.bubbleUp();
}
poll() {
if (this.isEmpty()) {
return null;
}
const root = this.heap[0];
const last = this.heap.pop();
if (this.heap.length > 0) {
this.heap[0] = last;
this.bubbleDown();
}
return root;
}
peek() {
return this.isEmpty() ? null : this.heap[0];
}
isEmpty() {
return this.heap.length === 0;
}
size() {
return this.heap.length;
}
bubbleUp() {
let index = this.heap.length - 1;
while (index > 0) {
const element = this.heap[index];
const parentIndex = Math.floor((index - 1) / 2);
const parent = this.heap[parentIndex];
if (parent <= element) {
break;
}
this.heap[index] = parent;
this.heap[parentIndex] = element;
index = parentIndex;
}
}
bubbleDown() {
let index = 0;
while (true) {
const leftChildIndex = 2 * index + 1;
const rightChildIndex = 2 * index + 2;
let smallest = index;
if (leftChildIndex < this.heap.length && this.heap[leftChildIndex] <
this.heap[smallest]) {
smallest = leftChildIndex;
}
if (rightChildIndex < this.heap.length && this.heap[rightChildIndex] <
this.heap[smallest]) {
smallest = rightChildIndex;
}
if (smallest === index) {
break;
}
const temp = this.heap[index];
this.heap[index] = this.heap[smallest];
this.heap[smallest] = temp;
index = smallest;
}
}
}
function mergeArrays(a, n, b, m) {
const minHeap = new PriorityQueue();
// Convert the second array into a min heap
for (const value of b) {
minHeap.offer(value);
}
// Start traversing the first array
for (let i = 0; i < n; i++) {
// If the current element is greater than the root of the min heap
if (a[i] > minHeap.peek()) {
// Remove and retrieve the minimum element from the min heap
const min = minHeap.poll();
// Swap the elements
const temp = a[i];
a[i] = min;
minHeap.offer(temp);
}
}
// Convert the min heap (second array) back to an array
let index = 0;
while (!minHeap.isEmpty()) {
b[index++] = minHeap.poll();
}
// Sort the second array
b.sort((x, y) => x - y);
}
// Driver Code
function main() {
const ar1 = [1, 5, 9, 10, 15, 20];
const ar2 = [2, 3, 8, 13];
const m = ar1.length;
const n = ar2.length;
mergeArrays(ar1, m, ar2, n);
console.log("After Merging :- \nFirst Array: " + JSON.stringify(ar1));
console.log("Second Array: " + JSON.stringify(ar2));
}
main();
OutputAfter Merging :-
First Array: 1 2 3 5 8 9
Second Array: 10 13 15 20
Time Complexity
: O(N*logM + M*logN)
Auxiliary Space
: O(1)
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