18. Common elements in 3 sorted arrays
18. Common elements in 3 sorted arrays
Problem link :- click here
package programs;
import java.util.*;
public class Array__18
{
static void printInsection(int a[], int b[], int c[])
{
int i, j, k;
i = 0;
j = 0;
k = 0;
while(i<a.length && j<b.length && k<c.length)
{
if( a[i]==b[j] && b[j]==c[k] )
{
System.out.print(a[i] + "\t");
i++; j++; k++;
}
else if( a[i] < b[j] )
i++;
else if( b[j] < c[k] )
j++;
else if( c[k] < a[i] )
k++;
}
}
public static void main(String[] args)
{
int m, n, o;
Scanner s = new Scanner(System.in);
System.out.print("Enter the size of the array 1 : ");
m = s.nextInt();
int array_1[] = new int[m];
System.out.println("Enter the elements of the array 1 :");
readArray(array_1, m);
System.out.print("Enter the size of the array 2 : ");
n = s.nextInt();
int array_2[] = new int[n];
System.out.println("Enter the elements of the array 1 :");
readArray(array_2, n);
System.out.print("Enter the size of the array 3 : ");
o = s.nextInt();
int array_3[] = new int[o];
System.out.println("Enter the elements of the array 1 :");
readArray(array_3, o);
System.out.println("\n\nIntersection of 3 sorted array is : ");
printInsection(array_1, array_2, array_3);
}
static void readArray(int arr[], int n)
{
Scanner s = new Scanner(System.in);
for(int i=0; i<n; i++)
arr[i] = s.nextInt();
}
}
Time complexity :- O(n1+n2+n3)
Space complexity :- O(n1+n2+n3) //if you want to store it
Comments
Post a Comment