Given two sorted arrays a[] and b[], where each array may contain duplicate elements , return the elements in the intersection of the two arrays. Intersection of two arrays is said to be elements that are common in both arrays. The intersection should not count duplicate elements and the result should contain items in sorted order.
Examples:
Input: a[] = [1, 1, 2, 2, 2, 4], b[] = [2, 2, 4, 4]
Output: [2, 4]
Explanation: 2 and 4 are only common elements in both the arrays.Input: a[] = [1, 2], b[] = [3, 4]
Output: []
Explanation: No common elements.Input: a[] = [1, 2, 3], b[] = [1, 2, 3]
Output: [1, 2, 3]
Explanation: All elements are common
Try It Yourself
Table of Content
[Naive Approach] Using Nested Loops - O(n*m) Time and O(1) Space
- Traverse through a[] and avoid duplicates while traversing. Since the arrays are sorted, we can avoid duplicates by matching with the previous element.
- For every element of a[], check if it is in b[], If Yes, then add it to the result and do not traverse further in b[] to avoid duplicates.
#include <iostream>
#include <vector>
using namespace std;
// Function to find the intersection of two arrays
// It returns a vector containing the common elements
vector<int> intersection(vector<int>& a, vector<int>& b) {
vector<int> res;
int m = a.size();
int n =