VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merge-two-sorted-arrays-in-o1-extra-space-using-quicksort-partition/

⇱ Merge two sorted arrays in O(1) extra space using QuickSort partition - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merge two sorted arrays in O(1) extra space using QuickSort partition

Last Updated : 23 Jul, 2025

Given two sorted arrays, arr[], brr[] of size N, and M, the task is to merge the two given arrays such that they form a sorted sequence of integers combining elements of both the arrays.

Examples:

Input: arr[] = {10}, brr[] = {2, 3}
Output: 2 3 10
Explanation: The merged sorted array obtained by taking all the elements from the both the arrays is {2, 3, 10}. 
Therefore, the required output is 2 3 10.

Input: arr[] = {1, 5, 9, 10, 15, 20}, brr[] = {2, 3, 8, 13}
Output: 1 2 3 5 8 9 10 13 15 20

Naive Approach: Refer to Merge two sorted arrays for the simplest approach to merge the two given arrays.
Time Complexity: O(N * M)
Auxiliary Space: O(1)

Space Optimized Approach: Refer to Merge two sorted arrays with O(1) extra space to merge the two given arrays without using any extra memory.
Time Complexity: O(N * M)
Auxiliary Space: O(1)

Efficient Space Optimized Approach: Refer to Efficiently merging two sorted arrays with O(1) extra space to merge the two given array without using any extra memory.
Time Complexity: O((N + M) * log(N + M))
Auxiliary Space: O(1)

Partition - based Approach: The idea is to consider the (N + 1)th element of the final sorted array as a pivot element and perform the quick sort partition around the pivot element. Finally, store the first N smaller elements of the final sorted array into the array, arr[] and the last M greater elements of the final sorted array into the array, brr[] in any order and sort both these arrays separately. Follow the steps below to solve the problem:

  1. Initialize a variable, say index to store the index of each element of the final sorted array.
  2. Find the (N + 1)th element of the final sorted array as a pivot element.
  3. Perform the quick sort partition around the pivot element.
  4. Finally, sort both the array arr[] and brr[] separately.

Below is the implementation of the above approach:


Output
1 2 4 5 7 9 10 

Time Complexity: O((N + M)log(N + M))
Auxiliary Space: O(1)

Efficient Approach: Refer to merge two sorted arrays to efficiently merge the two given arrays.
Time Complexity: O(N + M)
Auxiliary Space: O(N + M)

Comment