Find intersection of two sorted integer arrays
  • Posted: 5 years ago
  • Updated: 4 years ago
  • Edit
  • answers (1)
  • views (3853)

You are given two sorted integer arrays. How will you find their intersection?


Posted Answers

Let us assume array1 [ ] and array2 [ ] are the given two sorted arrays.


  • Compare the first element of array1 [ ] and array2 [ ].
  • If array1[0] < array2[0] , increment the index of array1[ ] .
  • If array1[0] > array2[0] , increment the index of array2[ ] .
  • If array1[0] = array2[0] , print any of them and increment both the indices.
  • Repeat the above steps until all the elements of the two arrays are visited.

Time complexity = \( O(Length\ of\ array1\ +\ Length\ of\ array2) \).

public static void findIntersection(int[] arr1, int[] arr2){

int i=0;
int j=0;

while(i < arr1.length & & j < arr2.length){

/* condition1 */
if(arr1[i] < arr2[j])
i++;

/* condition2 */
elseif(arr1[i] > arr2[j])
j++;

/* condition3 */
else{
system.out.println("Output is" + arr2[j]);
i++;
j++;
}
}
}

You need to Sign In to post your solution.