VOOZH about

URL: https://www.geeksforgeeks.org/dsa/union-of-two-arrays/

⇱ Union of Two Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Union of Two Arrays

Last Updated : 23 Feb, 2026

Given two arrays a[] and b[], Return union of both the arrays in any order.
Note: Union of two arrays is an array having all distinct elements that are present in either array.

Examples:

Input : a[] = [1, 2, 3, 2, 1], b[] = [3, 2, 2, 3, 3, 2]
Output : [3, 2, 1]
Explanation: 3, 2 and 1 are the distinct elements present in either array.

Input : a[] = [1, 2, 3], b[] = [4, 5, 6]
Output : [1, 2, 3, 4, 5, 6]
Explanation: 1, 2, 3, 4, 5 and 6 are the elements present in either array.

[Naive Approach] Using Nested Loops

The idea is to traverse both the arrays a[] and b[] and for each element, check if the element is present in the result or not. If not, then add this element to the result.


Output
1 2 3 

Time Complexity: O((n + m)2), where n is size of a[] and m is size of b[]

  • Inserting all elements from first array will take O(n2) time.
  • In the worst case, there will be no common elements in a[] and b[]. So, while inserting elements from second array, the first element needs n comparisons, the second element needs (n + 1) comparisons and so on. So total comparisons will be n + (n + 1) + (n + 2) ... (n + m) = O(n*m + m2) time.
  • So, total time complexity = O((n + m)2)

Auxiliary Space: O(1)

[Expected Approach] Using Hash Set - O(n+m) Time and O(n+m) Space

The idea is to use a Hash Set, which helps in keeping only unique elements by removing duplicates. We first create an empty Hash Set and add elements from both arrays. The Hash Set ensures that no duplicates are stored. After adding all the elements, we can create the final union array by iterating through the Hash Set.


Output
3 2 1 

Related Articles:

Comment
Article Tags: