Java Program to Print uncommon elements from two sorted arrays
Last Updated :
13 Jun, 2022
Given two sorted arrays of distinct elements, we need to print those elements from both arrays that are not common. The output should be printed in sorted order.
Examples :
Input : arr1[] = {10, 20, 30}
arr2[] = {20, 25, 30, 40, 50}
Output : 10 25 40 50
We do not print 20 and 30 as these
elements are present in both arrays.
Input : arr1[] = {10, 20, 30}
arr2[] = {40, 50}
Output : 10 20 30 40 50
The idea is based on merge process of merge sort. We traverse both arrays and skip common elements.
Java
import java.io.*;
class GFG {
static void printUncommon( int arr1[],
int arr2[], int n1, int n2)
{
int i = 0 , j = 0 , k = 0 ;
while (i < n1 && j < n2) {
if (arr1[i] < arr2[j]) {
System.out.print(arr1[i] + " " );
i++;
k++;
}
else if (arr2[j] < arr1[i]) {
System.out.print(arr2[j] + " " );
k++;
j++;
}
else {
i++;
j++;
}
}
while (i < n1) {
System.out.print(arr1[i] + " " );
i++;
k++;
}
while (j < n2) {
System.out.print(arr2[j] + " " );
j++;
k++;
}
}
public static void main(String[] args)
{
int arr1[] = { 10 , 20 , 30 };
int arr2[] = { 20 , 25 , 30 , 40 , 50 };
int n1 = arr1.length;
int n2 = arr2.length;
printUncommon(arr1, arr2, n1, n2);
}
}
|
Time Complexity: O(n1 + n2), where n1 and n2 represents the size of the given two arrays.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Please refer complete article on Print uncommon elements from two sorted arrays for more details!
Share your thoughts in the comments
Please Login to comment...