
Input: ‘n’ = 5 ‘m’ = 3
‘a’ = [1, 2, 3, 4, 6]
‘b’ = [2, 3, 5]
Output: [1, 2, 3, 4, 5, 6]
Explanation: Common elements in ‘a’ and ‘b’ are: [2, 3]
Distinct elements in ‘a’ are: [1, 4, 6]
Distinct elements in ‘b’ are: [5]
Union of ‘a’ and ‘b’ is: [1, 2, 3, 4, 5, 6]
The first line contains two integers, ‘n’ and ‘m’, denoting the size of the array ‘a’ and ‘b’, respectively.
The following line contains ‘n’ integers, denoting the 'a'.
The next line contains ‘m’ integers, denoting the ‘b’.
Return the union of both arrays sorted in ascending order.
You don't need to print anything. Just implement the given function.
The solution to the problem can be to store all the elements of array ‘A’ and array ‘B’ in a set.
This way, all the elements of array ‘A’ and array ‘B’ will be included in the set.
Also, one number will not be present more than once (because we are using a set).
In the end, we can take all the elements of the set and store them in a ‘dynamic array’, then we can return it.
// Function to find the union of two sorted arrays
function sortedArray(int[] A, int[] B, int N, int M):
The solution to the problem can be to use two pointers, ‘i' and ‘j’, pointing to the 0th index of arrays ‘A’ and ‘B’, respectively. We will create an empty dynamic array to store the union of arrays ‘A’ and ‘B’. Using the pointers ‘i’ and ‘j’, we will traverse the respective arrays and insert distinct elements from ‘A’ and ‘B’ into the ‘unionArray’ dynamic array in ascending order.
While traversing, we may encounter the following three cases:
After traversing, if any elements are left in ‘A’ or ‘B’ which are not traversed, then check for conditions and, based on that, insert them into ‘unionArray’.
// Function to find the union of two sorted arrays
function sortedArray(int[] A, int[] B, int N, int M):