Union of Two Arrays (original) (raw)

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.

Try It Yourselfredirect icon

Table of Content

[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.

C++ `

#include #include using namespace std;

vector findUnion(vector &a, vector &b) { vector res;

// Traverse through a[] and search every element
// a[i] in result
for (int i = 0; i < a.size(); i++) {

    // check if the element is already
    // in the result to avoid duplicates
    int j;
    for (j = 0; j < res.size(); j++)
        if (res[j] == a[i])
            break;
    if (j == res.size()) {
        res.push_back(a[i]);
    }
}

// Traverse through b[] and search every element
// b[i] in result
for (int i = 0; i < b.size(); i++) {

    // check if the element is already
    // in the result to avoid duplicates
    int j;
    for (j = 0; j < res.size(); j++)
        if (res[j] == b[i])
            break;
    if (j == res.size()) {
        res.push_back(b[i]);
    }
}
return res;

}

int main() {

vector<int> a = {1, 2, 3, 2, 1};
vector<int> b = {3, 2, 2, 3, 3, 2};

vector<int> res = findUnion(a, b);

for (int i = 0; i < res.size(); i++)
    cout << res[i] << " ";
return 0;

}

C

#include <stdio.h> #include <stdlib.h>

int *findUnion(int a[], int n, int b[], int m, int *size) {

// Allocate enough space for the 
// result (maximum possible size)
int *res = (int *)malloc((m + n) * sizeof(int));
int index = 0;

// Traverse through a[] and 
// search every element
for (int i = 0; i < n; i++) {

    // Check if the element is already
    // in the result to avoid duplicates
    int j;
    for (j = 0; j < index; j++) {
        if (res[j] == a[i])
            break;
    }
    if (j == index) {
        res[index++] = a[i];
    }
}

// Traverse through b[] and 
// search every element
for (int i = 0; i < m; i++) {
    
    // Check if the element is already
    // in the result to avoid duplicates
    int j;
    for (j = 0; j < index; j++) {
        if (res[j] == b[i])
            break;
    }
    if (j == index) {
        res[index++] = b[i];
    }
}

// Update the size of the result array
*size = index;
return res; 

}

int main() { int a[] = {1, 2, 3, 2, 1}; int b[] = {3, 2, 2, 3, 3, 2}; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); int size;

int *result = findUnion(a, n, b, m, &size);

for (int i = 0; i < size; i++)
    printf("%d ", result[i]);

free(result);
return 0;

}

Java

import java.util.ArrayList;

class GfG { static ArrayList findUnion(int[] a, int[] b) { ArrayList res = new ArrayList<>();

    // Traverse through a[] and search
    // every element a[i] in result
    for (int num : a) {

        // check if the element is already in
        // the result to avoid duplicates
        if (!res.contains(num)) {
            res.add(num);
        }
    }

    // Traverse through b[] and search
    // every element b[i] in result
    for (int num : b) {

        // check if the element is already in
        // the result to avoid duplicates
        if (!res.contains(num)) {
            res.add(num);
        }
    }
    return res;
}

public static void main(String[] args) {
  
    int[] a = { 1, 2, 3, 2, 1 };
    int[] b = { 3, 2, 2, 3, 3, 2 };

    ArrayList<Integer> res = findUnion(a, b);

    for (int num : res) {
        System.out.print(num + " ");
    }
}

}

Python

def findUnion(a, b): res = []

# Traverse through a[] and search every element
# a[i] in result
for i in range(len(a)):

    # check if the element is already
    # in the result to avoid duplicates
    j = 0
    while j < len(res):
        if res[j] == a[i]:
            break
        j += 1

    if j == len(res):
        res.append(a[i])

# Traverse through b[] and search every element
# b[i] in result
for i in range(len(b)):

    # check if the element is already
    # in the result to avoid duplicates
    j = 0
    while j < len(res):
        if res[j] == b[i]:
            break
        j += 1
    if j == len(res):
        res.append(b[i])

return res

if name == "main": a = [1, 2, 3, 2, 1] b = [3, 2, 2, 3, 3, 2]

res = findUnion(a, b)

for value in res:
    print(value, end=" ")

C#

using System; using System.Collections.Generic;

class GfG { static List findUnion(int[] a, int[] b) { List res = new List();

    // Traverse through a[] and search
    // every element a[i] in result
    foreach(var num in a) {

        // check if the element is already
        // in the result to avoid duplicates
        if (!res.Contains(num)) {
            res.Add(num);
        }
    }

    // Traverse through b[] and search
    // every element b[i] in result
    foreach(var num in b) {

        // check if the element is already
        // in the result to avoid duplicates
        if (!res.Contains(num)) {
            res.Add(num);
        }
    }

    return res;
}

static void Main() {
    int[] a = { 1, 2, 3, 2, 1 };
    int[] b = { 3, 2, 2, 3, 3, 2 };

    List<int> res = findUnion(a, b);

    foreach(var num in res) {
        Console.Write(num + " ");
    }
}

}

JavaScript

function findUnion(a, b) { let res = [];

// Traverse through a[] and search every element
// a[i] in result
for (let i = 0; i < a.length; i++) {

    // check if the element is already 
    // in the result to avoid duplicates
    let j;
    for (j = 0; j < res.length; j++) 
        if (res[j] === a[i]) 
            break;
    if (j === res.length) {
        res.push(a[i]);
    }
}

// Traverse through b[] and search every element
// b[i] in result
for (let i = 0; i < b.length; i++) {

    // check if the element is already 
    // in the result to avoid duplicates
    let j;
    for (j = 0; j < res.length; j++) 
        if (res[j] === b[i]) 
            break;
    if (j === res.length) {
        res.push(b[i]);
    }
}
return res;

}

// Driver Code const a = [1, 2, 3, 2, 1]; const b = [3, 2, 2, 3, 3, 2]; const res = findUnion(a, b); console.log(res.join(" "));

`

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

**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.

C++ `

#include #include #include using namespace std;

vector findUnion(vector& a, vector& b) { unordered_set st;

// Put all elements of a[] in st
for (int i = 0; i < a.size(); i++) 
      st.insert(a[i]);
  
  // Put all elements of b[] in st
for (int i = 0; i < b.size(); i++) 
      st.insert(b[i]);
  
vector<int> res;                            
  
  // iterate through the set to 
  // fill the result array 
  for(auto it: st) 
      res.push_back(it);

return res;

}

int main() { vector a = {1, 2, 3, 2, 1}; vector b = {3, 2, 2, 3, 3, 2};

vector<int> res = findUnion(a, b);

for (int i = 0; i < res.size(); i++) 
    cout << res[i] << " ";

return 0;

}

Java

import java.util.HashSet; import java.util.ArrayList;

class GfG { static ArrayList findUnion(int[] a, int[] b) { HashSet st = new HashSet<>();

    // Put all elements of a[] in st
    for (int num : a)
        st.add(num);

    // Put all elements of b[] in st
    for (int num : b)
        st.add(num);
    
      ArrayList<Integer> res = new ArrayList<> ();
  
    // iterate through the set 
    // to fill the result array 
    for(int it: st) 
        res.add(it);

    return res;
}

public static void main(String[] args) {
    int[] a = {1, 2, 3, 2, 1};
    int[] b = {3, 2, 2, 3, 3, 2};

    ArrayList<Integer> res = findUnion(a, b);

    for (int num : res)
        System.out.print(num + " ");
}

}

Python

def findUnion(a, b): st = set()

# Put all elements of a[] in st
for i in range(len(a)):
    st.add(a[i])

# Put all elements of b[] in st
for i in range(len(b)):
    st.add(b[i])

res = []                            

# iterate through the set 
# to fill the result array 
for it in st:
    res.append(it)

return res

if name == "main": a = [1, 2, 3, 2, 1] b = [3, 2, 2, 3, 3, 2]

res = findUnion(a, b)

for i in range(len(res)):
    print(res[i], end = ' ')

C#

using System; using System.Collections.Generic;

class GfG { static List findUnion(int[] a, int[] b) { HashSet st = new HashSet();

    // Put all elements of a[] in st
    foreach (var num in a) {
        st.Add(num);
    }

    // Put all elements of b[] in st
    foreach (var num in b) {
        st.Add(num);
    }

    // Convert the set to a list
    return new List<int>(st);
}

static void Main() {
    int[] a = {1, 2, 3, 2, 1};
    int[] b = {3, 2, 2, 3, 3, 2};

    List<int> res = findUnion(a, b);

    foreach (var num in res) {
        Console.Write(num + " ");
    }
}

}

JavaScript

function findUnion(a, b) { const st = new Set();

// Put all elements of a[] in st
for (let i = 0; i < a.length; i++) 
    st.add(a[i]);

// Put all elements of b[] in st
for (let i = 0; i < b.length; i++) 
    st.add(b[i]);

const res = [];                            

// iterate through the set 
// to fill the result array 
for (let it of st) 
    res.push(it);

return res;

}

// Driver Code const a = [1, 2, 3, 2, 1]; const b = [3, 2, 2, 3, 3, 2];

const res = findUnion(a, b);

console.log(res.join(" "));

`

**Related Articles: