VOOZH about

URL: https://www.geeksforgeeks.org/dsa/merging-two-unsorted-arrays-sorted-order/

⇱ Merging two unsorted arrays in sorted order - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Merging two unsorted arrays in sorted order

Last Updated : 31 Jul, 2025

Given two integer arrays arr1[] and arr2[], merge them into a single array such that the resulting array contains only unique elements from both arrays. Additionally, the final array should be sorted in ascending order.

Examples :

Input: arr1[] = [11, 1, 8], arr2[] = [10, 11]
Output: [1, 8, 10, 11]
Explanation: The ouput array after merging both the arrays and removing duplicates is [1 8, 10, 11].

Input: arr1[] = [7, 1, 5, 3, 9], arr2[] = [8, 4, 3, 5, 2, 6]
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Explanation: The ouput array after merging both the arrays and removing duplicates is [1, 2, 3, 4, 5, 6, 7, 8, 9].

[Approach 1] First concatenate then sort

The idea is to merge two unsorted arrays into a single list, then sort that list and remove any duplicate elements to get a sorted arrays of unique values.


Output
1 8 10 11 

Time Complexity: O((n + m)*log(n + m))
Auxiliary Space: O(n + m)

[Approach 2] First sort then merge

First, sorts both input arrays individually. Then, merge them into a result array by comparing elements one by one from both sorted arrays, maintaining the overall sorted order. Any remaining elements from either array are appended after one finishes.


Output
 1 8 10 11

Time Complexity: O(nlog(n) + mlog(m)) 
AuxiliarySpace: O(1)

Comment
Article Tags:
Article Tags: