Union of Two Arrays with Distinct Elements (original) (raw)

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.

Table of Content

[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 onlyif they were not present in a[]. This ensures that all the elements from both arrays are included, with no **duplicates.

C++ `

// C++ program to find union of two arrays // with distinct elements

#include #include using namespace std;

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

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

    // check if the element was present in a[]
    // to avoid duplicates
    int j;
    for (j = 0; j < a.size(); j++) {
        if (a[j] == b[i])
            break;
    }

    // if not already present then
    // add it to result
    if (j == a.size()) {
        res.push_back(b[i]);
    }
}
return res;

}

int main() {

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

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 *resSize) { int *res = (int *)malloc((n + m) * sizeof(int)); int index = 0;

// Copy elements of a[] to result
for (int i = 0; i < n; i++) {
    res[index++] = a[i];
}

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

    // check if the element was present in a[]
    // to avoid duplicates
    int j;
    for (j = 0; j < n; j++) {
        if (a[j] == b[i])
            break;
    }

    // if not already present then
    // add it to result
    if (j == n) {
        res[index++] = b[i];
    }
}

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

}

int main() { int a[] = {1, 2, 3}; int b[] = {5, 2, 7}; int resSize;

int *res = findUnion(a, 3, b, 3, &resSize);

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

return 0;

}

Java

// Java program to find union of two arrays // with distinct elements

import java.util.ArrayList;

class GfG {

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

    // Add all elements from array a to res
    for (int i = 0; i < a.length; i++) {
        res.add(a[i]);
    }

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

        // check if the element was present in a[]
        // to avoid duplicates
        int j;
        for (j = 0; j < a.length; j++) {
            if (a[j] == b[i])
                break;
        }

        // If not already present, add it to res
        if (j == a.length) {
            res.add(b[i]);
        }
    }

    return res;
}

public static void main(String[] args) {

    int[] a = { 1, 2, 3 };
    int[] b = { 5, 2, 7 };

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

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

}

Python

Python program to find union of two arrays

with distinct elements

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

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

    # check if the element was present in a[]
    # to avoid duplicates
    if b[i] not in a:

        # if not already present then
        # add it to result
        res.append(b[i])

return res

if name == "main":

a = [1, 2, 3]
b = [5, 2, 7]

res = findUnion(a, b)

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

C#

// C# program to find union of two arrays // with distinct elements

using System; using System.Collections.Generic;

class GfG {

static List<int> findUnion(int[] a, int[] b) {

    // Create a list for the result and initialize it
    // with elements from array a[]
    List<int> res = new List<int>(a);

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

        // check if the element was present in a[]
        // to avoid duplicates
        int j;
        for (j = 0; j < a.Length; j++) {
            if (a[j] == b[i])
                break;
        }

        // If not already present, add it to the result
        if (j == a.Length) {
            res.Add(b[i]);
        }
    }
    return res;
}

static void Main() {

    int[] a = { 1, 2, 3 };
    int[] b = { 5, 2, 7 };

    List<int> res = findUnion(a, b);
    for (int i = 0; i < res.Count; i++) {
        Console.Write(res[i] + " ");
    }
}

}

JavaScript

// JavaScript program to find union of two arrays // with distinct elements

function findUnion(a, b) {

// create a result array with
// content of array a[]
let res = [...a ];

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

    // check if the element was present in a[]
    // to avoid duplicates
    if (!a.includes(b[i])) {

        // if not already present then
        // add it to result
        res.push(b[i]);
    }
}
return res;

}

let a = [ 1, 2, 3 ]; let b = [ 5, 2, 7 ];

let res = findUnion(a, b);

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

`

**Time Complexity: O(n * m), 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.

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

**Related Articles: