Open In App

Union of Two Arrays with Distinct Elements

Last Updated : 04 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

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

#include <iostream>
#include <vector>
using namespace std;

vector<int> findUnion(vector<int> &a, vector<int> &b) {
    vector<int> 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(" "));

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:


Next Article
Practice Tags :

Similar Reads