21 Dec 2013

Intersection and Union of Arrays

Problem Statement: 
         Find the Intersection and Union of Arrays

Solution:
 Below we will find solution of problem in O(n) and assuming the arrays are already sorted.

Full Source Code : LINK

Intersection Logic: 
1. If 1st array element is smaller , increment its index
2. If 2nd array element is smaller , increment its index.
3. If equal, print either , and increment both.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
/**
  * Intersection of Arrays
  */
 public void intersection() {
  int i=0;
  int j=0;

  while(i < arr1.length && j < arr2.length)
  {
   if(arr1[i] < arr2[j])
    i++;
   else if(arr1[i] > arr2[j])
    j++;
   else
   {
    System.out.print(arr1[i++] + "\t");
    j++;
   }
  }
 }

Union Logic:
1. If element of 1st array is smaller print it, and increment index. 
2. If element of 2st array is smaller print it, and increment index.
3. If both are equal , print arr1 element and increment both indexes of both arrays
4. Print remaining array of the larger array.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
       /**
  * Union Of arrays
  */
 public void union() {
  int i=0,j=0;
  while(i < arr1.length && j < arr2.length)
  {
   if(arr1[i] < arr2[j])
    System.out.print(arr1[i++]);
   else if(arr1[i] > arr2[j])
    System.out.print(arr2[j++]);
   else
   {
    System.out.print(arr1[i++]);
    j++;
   }
   System.out.print("\t");
  }

  if(arr2.length > arr1.length)
   for(;j<arr2.length;System.out.println(arr2[j]),j++);
  else if(arr2.length < arr1.length)
   for( ; i<arr1.length;System.out.println(arr1[i]),i++);
 }


Please comment and post your suggestions.
Happy Coding!! :) 

No comments:

Post a Comment