DSAAGP100 - Editorial

Problem Statement

You are given two sorted arrays a and b. Your task is to find and print the count of common elements in both arrays.

Approach

To efficiently count the common elements in the two sorted arrays, we can use a two-pointer technique. This method allows us to traverse both arrays simultaneously, leveraging their sorted nature:

  1. Initialize Pointers and Count:

    • Use two pointers, i for array a and j for array b.

    • Start both pointers at the beginning of their respective arrays and initialize a variable count to 0 to track the number of common elements.

  2. Traverse the Arrays:

    • While both pointers are within the bounds of their arrays:
      • If a[i] is equal to b[j], we have found a common element. Increment count and move both pointers forward.

      • If a[i] is less than b[j], increment pointer i to check the next element in a.

      • If a[i] is greater than b[j], increment pointer j to check the next element in b.

  3. Print the Count:

  • After exiting the loop, print the value of count, which represents the total number of common elements found.

This approach is efficient because we only pass through each array once, making it faster than checking each element in one array against all elements in the other.

Time Complexity

  • O(n + m): The time complexity is linear with respect to the sum of the sizes of the two arrays, as each array is traversed at most once.

Space Complexity

  • O(1): The space complexity is constant, as only a few additional variables are used.