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

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}
**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^2) Time and O(1) Space

The idea is to add all elements from the first array **a[] to **result array. Then, iterate through the second array **b[] and add its elements to the **result only if they were not present in **a[]. Finally, sort the result array to get the union in sorted order.

C++ `

// C++ program to find union of two sorted arrays // with distinct elements using nested loops

#include #include #include using namespace std;

vector findUnion(vector &a, vector &b) { int n = a.size(), m = b.size(); vector res = a;

// Traverse through b[] and search every element
// b[i] in a[]
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 < n; j++) {
        if (a[j] == b[i])
            break;
    }

    // if not already present in a[] then
    // add it to result
    if (j == n) {
        res.push_back(b[i]);
    }
}
  sort(res.begin(), res.end());
return res;

}

int main() {

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

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

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

return 0;

}

C

// C program to find union of two sorted arrays // with distinct elements using nested loops

#include <stdio.h>

int compare(const void *a, const void b) { return ((int *)a - *(int *)b); }

int* findUnion(int *a, int n, int *b, int m, int *resSize) { int *res = (int *)malloc((n + m) * sizeof(int)); int k = 0;

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

// Traverse through b[] and search every element
// b[i] in a[]
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 < n; j++) {
        if (a[j] == b[i])
            break;
    }

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

// Resize the result array
res = (int *)realloc(res, k * sizeof(int));
*resSize = k;

qsort(res, *resSize, sizeof(int), compare);

return res;

}

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

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

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

}

Java

// Java program to find union of two sorted arrays // with distinct elements using nested loops

import java.util.ArrayList; import java.util.Arrays;

class GfG {

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

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

    // Traverse through b[] and search every element
    // b[i] in a[]
    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 < n; j++) {
            if (a[j] == b[i])
                break;
        }

        // if not already present then
        // add it to result
        if (j == n) {
            res.add(b[i]);
        }
    }
    
    // Sort the result
    res.sort(null);
    return res;
}

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

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

    for (int i = 0; i < res.size(); i++)
        System.out.print(res.get(i) + " ");
}

}

Python

Python program to find union of two sorted arrays

with distinct elements using nested loops

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

# 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
    if b[i] not in a:

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

res.sort()
return res

if name == "main":

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

res = findUnion(a, b)

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

C#

// C# program to find union of two sorted arrays // with distinct elements using nested loops

using System; using System.Collections;

class GfG { static ArrayList findUnion(int[] a, int[] b) { int n = a.Length, m = b.Length; ArrayList res = new ArrayList();

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

    // Traverse through b[] and search every element
    // b[i] in a[]
    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 < n; j++) {
            if (a[j] == b[i])
                break;
        }

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

    res.Sort();
    return res;
}

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

    ArrayList res = findUnion(a, b);

    for (int i = 0; i < res.Count; i++)
        Console.Write(res[i] + " ");
}

}

JavaScript

// JavaScript program to find union of two sorted arrays // with distinct elements using nested loops

function findUnion(a, b) { let n = a.length, m = b.length; let res = a.slice();

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

    // check if the element is already in the
    // result to avoid duplicates
    let 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.push(b[i]);
    }
}

res.sort((x, y) => x - y);
return res;

}

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

const 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)

**[Better Approach 1] Using Set - O((n+m)*log(n+m)) Time and O(n+m) Space

The approach is to insert all elements from both arrays, **a[] and **b[], into a set. Since a **set automatically removes duplicates, it gives us the union of the two arrays. Also, the set keeps the elements in sorted order, so after inserting them, we can store these sorted and unique elements in a result array.

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

[Better Approach 2] Using Binary Search - O****((n+m)*log(n+m))** Time and O(1) Space

The idea is to first add all elements from the first array into the result. Now, iterate over the second array and for each element, add the element to the result only if it was not present in the first array. Since the first array is **sorted, we can use Binary Search to search for an element in **log(n) time. After pushing all the elements to the result, sort the result.

C++ `

// C++ program to find union of two sorted arrays with // distinct elements using Binary Search

#include <bits/stdc++.h> using namespace std;

// Function to perform binary search int binarySearch(vector &arr, int lo, int hi, int target) { while (lo <= hi){ int mid = lo + (hi - lo) / 2;

    if (arr[mid] == target)
        return mid;
    if (arr[mid] < target)
        lo = mid + 1;
    else
        hi = mid - 1;
}
return -1;

}

vector findUnion(vector &a, vector &b) { vector res = a; int n = a.size(); int m = b.size();

for(int i = 0; i < m; i++) {
  
    // Binary Search for b[i] in array a[] 
    int idx = binarySearch(a, 0, n - 1, b[i]);
    if(idx == -1)
        res.push_back(b[i]);
}

// Sort the result to get union in sorted order
sort(res.begin(), res.end());
return res; 

}

int main() {

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

vector<int> res = findUnion(a, b);
for (int x : res) {
    cout << x << " ";
}

}

C

// C program to find union of two sorted arrays with // distinct elements using Binary Search

#include <stdio.h>

// Function to perform binary search int binarySearch(int arr[], int lo, int hi, int target) { while (lo <= hi) { int mid = lo + (hi - lo) / 2;

    if (arr[mid] == target)
        return mid;
    if (arr[mid] < target)
        lo = mid + 1;
    else
        hi = mid - 1;
}
return -1;

}

// Comparison function for qsort int compare(const int* a, const int* b) { return (*a > *b) - (*a < *b); }

int* findUnion(int a[], int n, int b[], int m, int* resSize) { int* res = (int*)malloc((n + m) * sizeof(int)); int index = 0;

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

for (int i = 0; i < m; i++) {
    
    // Binary Search for b[i] in array a[]
    int idx = binarySearch(a, 0, n - 1, b[i]);
    if (idx == -1) {
        res[index++] = b[i];
    }
}

// Sort the result to get union in sorted order
qsort(res, index, sizeof(int), compare);

*resSize = index;
return res;

}

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

int* res = findUnion(a, n, b, m, &resSize);
for (int i = 0; i < resSize; i++) {
    printf("%d ", res[i]);
}

free(res); 
return 0;

}

Java

// Java program to find union of two sorted arrays with // distinct elements using Binary Search

import java.util.ArrayList; import java.util.Arrays;

class GfG {

// Function to perform binary search
static int binarySearch(int[] arr, int lo, int hi, int target) {
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;

        if (arr[mid] == target)
            return mid;
        if (arr[mid] < target)
            lo = mid + 1;
        else
            hi = mid - 1;
    }
    return -1;
}

static ArrayList<Integer> findUnion(int[] a, int[] b) {
    ArrayList<Integer> res = new ArrayList<>();
    for (int num : a) {
        res.add(num);
    }
    int n = a.length;
    int m = b.length;

    for (int i = 0; i < m; i++) {
        
        // Binary Search for b[i] in array a[] 
        int idx = binarySearch(a, 0, n - 1, b[i]);
        if (idx == -1)
            res.add(b[i]);
    }

    // Sort the result to get union in sorted order
    Integer[] resultArray = res.toArray(new Integer[0]);
    Arrays.sort(resultArray);
    return new ArrayList<>(Arrays.asList(resultArray));
}

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

    ArrayList<Integer> res = findUnion(a, b);
    for (int x : res) {
        System.out.print(x + " ");
    }
}

}

Python

Python program to find union of two sorted arrays with

distinct elements using Binary Search

def binarySearch(arr, lo, hi, target): while lo <= hi: mid = lo + (hi - lo) // 2

    if arr[mid] == target:
        return mid
    if arr[mid] < target:
        lo = mid + 1
    else:
        hi = mid - 1
return -1

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

for i in range(m):
    
    # Binary Search for b[i] in array a[] 
    idx = binarySearch(a, 0, n - 1, b[i])
    if idx == -1:
        res.append(b[i])

# Sort the result to get union in sorted order
res.sort()
return res

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

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

C#

// C# program to find union of two sorted arrays with // distinct elements using Binary Search

using System; using System.Collections.Generic;

class GfG {

// Function to perform binary search
static int binarySearch(int[] arr, int lo, int hi, int target) {
    while (lo <= hi) {
        int mid = lo + (hi - lo) / 2;

        if (arr[mid] == target)
            return mid;
        if (arr[mid] < target)
            lo = mid + 1;
        else
            hi = mid - 1;
    }
    return -1;
}

static List<int> findUnion(int[] a, int[] b) {
    List<int> res = new List<int>(a);
    int n = a.Length;
    int m = b.Length;

    for (int i = 0; i < m; i++) {
      
        // Binary Search for b[i] in array a[]
        int idx = binarySearch(a, 0, n - 1, b[i]);
        if (idx == -1)
            res.Add(b[i]);
    }

    // Sort the result to get union in sorted order
    res.Sort();
    return res;
}

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

    List<int> res = findUnion(a, b);
    foreach (int x in res) {
        Console.Write(x + " ");
    }
}

}

JavaScript

// JavaScript program to find union of two sorted arrays
// with distinct elements using Binary Search

// Function to perform binary search function binarySearch(arr, lo, hi, target) { while (lo <= hi) { let mid = lo + Math.floor((hi - lo) / 2);

    if (arr[mid] === target)
        return mid;
    if (arr[mid] < target)
        lo = mid + 1;
    else
        hi = mid - 1;
}
return -1;

}

function findUnion(a, b) { let res = a.slice(); let n = a.length; let m = b.length;

for (let i = 0; i < m; i++) {
    
    // Binary Search for b[i] in array a[] 
    let idx = binarySearch(a, 0, n - 1, b[i]);
    if (idx === -1)
        res.push(b[i]);
}

// Sort the result to get union in sorted order
res.sort((x, y) => x - y);
return res; 

}

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

const res = findUnion(a, b); console.log(res.join(" "));

`

**Time Complexity: O((n+m)*log(m+n)), as we are sorting the result array.
**Auxiliary Space: O(1)

[Expected Approach] Using Merge Step of Merge Sort - O(n+m) Time and O(1) Space

The idea is to finds the union of two sorted arrays using merge step in merge sort. We maintain two pointers to traverse both arrays simultaneously.

Once one array is fully traversed, any remaining elements from the other array are added.

C++ `

// C++ program to find union of two sorted arrays with // distinct elements using merge step of merge sort

#include <bits/stdc++.h> using namespace std;

vector findUnion(vector& a, vector& b) { vector res; int n = a.size(); int m = b.size();

// this is similar to merge step of merge sort
int i = 0, j = 0;    
while(i < n && j < m) {
    
      // add the smaller element from the current elements
    // and move accordingly
    if(a[i] < b[j]) {
          res.push_back(a[i]);
        i++;
    }
    else if(a[i] > b[j]) {
          res.push_back(b[j]);
        j++;
    }
  
    // If equal, then add to result and move both 
    else {
        res.push_back(a[i]);
        i++;
        j++;
    }
}
  
  // Add the remaining elements of a[]
  while (i < n) {
      res.push_back(a[i]);
      i++;
}

  // Add the remaining elements of b[]
  while (j < m) {
      res.push_back(b[j]);
      j++;
}
return res; 

}

int main() {

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

vector<int> res = findUnion(a, b);
for (int x : res) {
    cout << x << " ";
}

}

C

// C program to find union of two sorted arrays with // distinct elements using merge step of merge sort

#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 i = 0, j = 0, k = 0;

// This is similar to merge of merge sort
while (i < n && j < m) {
    
    // select and add the smaller element 
    // from the current elements and move accordingly
    if (a[i] < b[j]) {
        res[k++] = a[i++];
    }
    else if (a[i] > b[j]) {
        res[k++] = b[j++];
    }
  
    // If equal, then add to result and move both 
    else {
        res[k++] = a[i++];
        j++;
    }
}

// Add the remaining elements of a[]
while (i < n) {
    res[k++] = a[i++];
}

// Add the remaining elements of b[]
while (j < m) {
    res[k++] = b[j++];
}

*resSize = k;
return res; 

}

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

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

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

free(res);
return 0;

}

Java

// Java program to find union of two sorted arrays with // distinct elements using merge step of merge sort

import java.util.*;

class GfG { static ArrayList findUnion(int a[], int b[]) { ArrayList res = new ArrayList<>(); int n = a.length; int m = b.length; int i = 0, j = 0;

    // This is similar to merge of merge sort
    while (i < n && j < m) {

        // select and add the smaller element 
        // from the current elements and move accordingly
        if (a[i] < b[j]) {
            res.add(a[i++]);
        } 
        else if (a[i] > b[j]) {
            res.add(b[j++]);
        }

        // If equal, then add to result and move both 
        else {
            res.add(a[i++]);
            j++;
        }
    }

    // Add the remaining elements of a[]
    while (i < n)
        res.add(a[i++]);

    // Add the remaining elements of b[]
    while (j < m)
        res.add(b[j++]);

    return res;
}

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

    ArrayList<Integer> res = findUnion(a, b);
    for (int x : res) {
        System.out.print(x + " ");
    }
}

}

Python

Python program to find union of two sorted arrays with

distinct elements using merge step of merge sort

def findUnion(a, b): res = [] n, m = len(a), len(b) i, j = 0, 0

# This is similar to merge of merge sort
while i < n and j < m:
    
    # select and add the smaller element 
    # from the current elements and move accordingly
    if a[i] < b[j]:
        res.append(a[i])
        i += 1
    elif a[i] > b[j]:
        res.append(b[j])
        j += 1
    
    # If equal, then add to result and move both 
    else:
        res.append(a[i])
        i += 1
        j += 1

# Add the remaining elements of a[]
while i < n:
    res.append(a[i])
    i += 1

# Add the remaining elements of b[]
while j < m:
    res.append(b[j])
    j += 1

return res

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

res = findUnion(a, b)
for i in res:
    print(i, end=" ")

C#

// C# program to find union of two sorted arrays with // distinct elements using merge step of merge sort

using System; using System.Collections.Generic;

class GfG { static List FindUnion(int[] a, int[] b) { List res = new List(); int n = a.Length; int m = b.Length; int i = 0, j = 0;

    // This is similar to merge of merge sort
    while (i < n && j < m) {

        // select and add the smaller element 
        // from the current elements and move accordingly
        if (a[i] < b[j]) {
            res.Add(a[i]);
            i++;
        } else if (a[i] > b[j]) {
            res.Add(b[j]);
            j++;
        }

        // If equal, then add to result and move both 
        else {
            res.Add(a[i]);
            i++;
            j++;
        }
    }

    // Add the remaining elements of a[]
    while (i < n) {
        res.Add(a[i]);
        i++;
    }

    // Add the remaining elements of b[]
    while (j < m) {
        res.Add(b[j]);
        j++;
    }
    return res;
}

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

    List<int> res = FindUnion(a, b);
    foreach (int x in res) {
        Console.Write(x + " ");
    }
}

}

JavaScript

// JavaScript program to find union of two sorted arrays with // distinct elements using merge step of merge sort

function findUnion(a, b) { let res = []; let n = a.length, m = b.length; let i = 0, j = 0;

// This is similar to merge of merge sort
while (i < n && j < m) {

    // select and add the smaller element 
    // from the current elements and move accordingly
    if (a[i] < b[j]) {
        res.push(a[i]);
        i++;
    } else if (a[i] > b[j]) {
        res.push(b[j]);
        j++;
    }

    // if equal, then add to result and move both 
    else {
        res.push(a[i]);
        i++;
        j++;
    }
}

// Add the remaining elements of a[]
while (i < n) {
    res.push(a[i]);
    i++;
}

// Add the remaining elements of b[]
while (j < m) {
    res.push(b[j]);
    j++;
}
return res;

}

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

let res = findUnion(a, b); console.log(res.join(" "));

`

**Time Complexity: O(n+m), where **n is the size of array **a[] and **m is the size of array **b[].
**Auxiliary Space: O(1)

**Related Articles: