Union Of 2 Sorted with duplicate Problem GFG
Given two sorted arrays a[] and b[], where each array may contain duplicate elements , the task is to return the elements in the union of the two arrays in sorted order.
Union of two arrays can be defined as the set containing distinct common elements that are present in either of the arrays.
Examples:
Input: a[] = [1, 2, 3, 4, 5], b[] = [1, 2, 3, 6, 7]
Output: 1 2 3 4 5 6 7
Explanation: Distinct elements including both the arrays are: 1 2 3 4 5 6 7.
Input: a[] = [2, 2, 3, 4, 5], b[] = [1, 1, 2, 3, 4]
Output: 1 2 3 4 5
Explanation: Distinct elements including both the arrays are: 1 2 3 4 5.
Input: a[] = [1, 1, 1, 1, 1], b[] = [2, 2, 2, 2, 2]
Output: 1 2
Explanation: Distinct elements including both the arrays are: 1 2.
//{ Driver Code Starts
// Initial Template for Java
import java.io.*;
import java.lang.*;
import java.util.*;
class Main {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine().trim());
while (t-- > 0) {
// First array input
String[] str1 = br.readLine().trim().split(
" "); // Read the first line and split by spaces
int n = str1.length;
int[] a = new int[n];
for (int i = 0; i < n; i++) {
a[i] = Integer.parseInt(str1[i]); // Convert each element to an integer
}
// Second array input
String[] str2 = br.readLine().trim().split(
" "); // Read the second line and split by spaces
int m = str2.length;
int[] b = new int[m];
for (int i = 0; i < m; i++) {
b[i] = Integer.parseInt(str2[i]); // Convert each element to an integer
}
Solution obj = new Solution();
ArrayList<Integer> res = new ArrayList<Integer>();
res = obj.findUnion(a, b);
for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + " ");
System.out.println();
System.out.println("~");
}
}
}
// } Driver Code Ends
// User function Template for Java
// a,b : the arrays
class Solution {
// Function to return a list containing the union of the two arrays.
public static ArrayList<Integer> findUnion(int a[], int b[]) {
// add your code here
HashSet<Integer> set = new HashSet<>();
for(int i:a)
{
set.add(i);
}
for(int j:b)
{
set.add(j);
}
ArrayList<Integer> result = new ArrayList<>(set);
Collections.sort(result);
return result;
}
}
Comments
Post a Comment