Be the first user to complete this post

  • 0
Add to List

Find intersection between Two Sorted Arrays.

Objective: Given two sorted arrays, Find the intersection points between them.

Examples:

int[] a = { 1, 2, 3, 6, 8, 10 };
int[] b = { 4, 5, 6, 11, 15, 20 };
Output: Intersection point is : 6

Approach:

Naive Approach: Use 2 loops and compare each element in both arrays and as soon as you find the intersection point, return it. Time Complexity - O(n2).

Better Approach: Time Complexity - O(n)

  • Say Arrays are arrA[] and arrB[] and indexes for navigation are x and y respectively.
  • Since arrays are sorted, compare the first element of both arrays.(x=0, y=0)
  • If both elements are the same, we have our intersection point and return it.
  • Else if element of arrA[x] > element of arrB[y], increase the arrB[] index, y++.
  • Else if element of arrA[x] < element of arrB[y], increase the arrA[] index, x++.
  • If any of the arrays gets over that means you have not found the intersection point. return -1.

Code:


Output:

Intersection point is : 6



Also Read: