Union of Two Sorted Arrays

Last updated: 29th Aug, 2020

  

Problem Statment

Given two sorted arrays arr[] and brr[] of size N and M respectively.
Find the union of these two arrays.

Input Format
M=7 arr1 = [1,2,2,4,5,5,6] N=7 arr2 = [6,6,7,7,8,9,9]

Output Format
{1,2,4,5,6,7,8,9}
Approach :

1. Accept elements in the array arr[] and brr[] and store their lenght in two separate  variable.
2. Merge the two array using "+" operator and store it in a variable .
3. Sort the merged array using "sorted()" function
4. Store the sorted merged array in set [Since set does not contain duplicate  elements]
5. Return the final array.

Python Code

def union (a,b,m,n):
#add both the array 
    result = a+b
    #return the sorted array
    #set() does not contain any duplicate elemenet
    return sorted(set(result))
                        
#Driver's code 
a=[2,2,3,4,5]
b=[1,1,2,3,4]
m= len(a)
n= len(b)
print(union(a,b,m,n))