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.
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> findUnion(vector<int> &a, vector<int> &b) {
vector<int> 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<Integer> findUnion(int[] a, int[] b) {
ArrayList<Integer> 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<int> findUnion(int[] a, int[] b) {
List<int> res = new List<int>();
// 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[]
- 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.
C++
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
vector<int> findUnion(vector<int>& a, vector<int>& b) {
unordered_set<int> 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<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;
}
Java
import java.util.HashSet;
import java.util.ArrayList;
class GfG {
static ArrayList<Integer> findUnion(int[] a, int[] b) {
HashSet<Integer> 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<int> findUnion(int[] a, int[] b) {
HashSet<int> st = new HashSet<int>();
// 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:
Similar Reads
Union of Two Sorted Arrays Given two sorted arrays a[] and b[], the task is to to return union of both the arrays in sorted order. Union of two arrays is an array having all distinct elements that are present in either array. The input arrays may contain duplicates.Examples:Input: a[] = {1, 1, 2, 2, 2, 4}, b[] = {2, 2, 4, 4}O
15+ min read
Union of Two Arrays with Distinct Elements 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,
7 min read
Intersection of two Arrays Given two arrays a[] and b[], find their intersection â the unique elements that appear in both. Ignore duplicates, and the result can be in any order.Input: a[] = [1, 2, 1, 3, 1], b[] = [3, 1, 3, 4, 1]Output: [1, 3]Explanation: 1 and 3 are the only common elements and we need to print only one occu
12 min read
Merge two sorted arrays Given two sorted arrays, the task is to merge them in a sorted manner.Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8}Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} Table of Content[Naive Approach] Concatenat
10 min read
Union of Two Sorted Arrays with Distinct Elements Given two sorted arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in sorted 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[] = {2, 5, 7}Output: {1, 2, 3, 5, 7}Explan
15+ min read