VOOZH about

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

⇱ Union of Two Arrays with Distinct Elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Union of Two Arrays with Distinct Elements

Last Updated : 23 Jul, 2025

Given two arrays a[] and b[] with distinct elements, the task is to 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}, b[] = {5, 2, 7}
Output: {1, 2, 3, 5, 7}
Explanation: 1, 2, 3, 5 and 7 are the distinct elements present in either array.

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

[Naive Approach] Using Nested Loops - O(n * m) Time and O(1) Space

The idea is to add all elements from the first array a[] to a result array. Then iterate through the second array b[] and add its elements to the result only if they were not present in a[]. This ensures that all the elements from both arrays are included, with no duplicates.


Output
1 2 3 5 7 

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

  • Copying all elements from a[] to res[] takes O(n) time.
  • Now in the worst case, there will be no common elements in a[] and b[]. So, for every element of b[], we need to make n comparisons in a[]. So, this will take O(n * m).
  • So, overall time complexity = O(n * m)

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.

To know more about the implementation, please refer to the efficient approach in Union of Two Arrays.

Related Articles:

Comment
Article Tags: