Open In App

Intersection of Two Sorted Arrays

Last Updated : 11 Oct, 2024
Suggest changes
Share
Like Article
Like
Report

Given two sorted arrays a[] and b[], the task is to return intersection. 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

[Naive Approach] Using Nested Loops - O(n*m) Time and O(1) Space

  1. Traverse through a[] and avoid duplicates while traversing. Since the arrays are sorted, we can avoid duplicates by matching with the previous element.
  2. 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.
C++
#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 = b.size();     for(int i = 0; i < m; i++) {    // Note that duplicates must be   // consecutive in a sorted array  if(i > 0 && a[i - 1] == a[i])  continue;    // Since we are only searchin distint  // elements of a[] in b[] and we break as   // soon we find a match, we get only  // distinct elements in result  for(int j = 0; j < n; j++) {  if(a[i] == b[j]) {  res.push_back(a[i]);  break;   }  }  }  return res; } int main() {  vector<int> a = {3, 5, 10, 10, 10, 15, 15, 20};  vector<int> b = {5, 10, 10, 15, 30};  vector<int> res = intersection(a, b);   for (int x : res) {  cout << x << " ";  } } 
C
#include <stdio.h> // Function to find the intersection of two arrays // It returns the result array containing the common elements void intersection(int a[], int m, int b[], int n, int res[], int *res_size) {  for (int i = 0; i < m; i++) {  // Note that duplicates must be   // consecutive in a sorted array  if (i > 0 && a[i - 1] == a[i])  continue;  // Since we are only searching distinct  // elements of a[] in b[] and we break as   // soon we find a match, we get only  // distinct elements in result  for (int j = 0; j < n; j++) {  if (a[i] == b[j]) {  res[(*res_size)++] = a[i];  break;  }  }  } } int main() {  int a[] = {3, 5, 10, 10, 10, 15, 15, 20};  int b[] = {5, 10, 10, 15, 30};  int res[10];  int res_size = 0;   intersection(a, 8, b, 5, res, &res_size);  for (int i = 0; i < res_size; i++) {  printf("%d ", res[i]);  }  return 0; } 
Java
import java.util.ArrayList; import java.util.List; class GfG {  // Function to find the intersection of two arrays  // It returns a list containing the common elements  static List<Integer> intersection(int[] a, int[] b) {  List<Integer> res = new ArrayList<>();  int m = a.length;  int n = b.length;  for (int i = 0; i < m; i++) {  // Note that duplicates must be   // consecutive in a sorted array  if (i > 0 && a[i - 1] == a[i])  continue;  // Since we are only searching distinct  // elements of a[] in b[] and we break as   // soon we find a match, we get only  // distinct elements in result  for (int j = 0; j < n; j++) {  if (a[i] == b[j]) {  res.add(a[i]);  break;  }  }  }  return res;  }  public static void main(String[] args) {  int[] a = {3, 5, 10, 10, 10, 15, 15, 20};  int[] b = {5, 10, 10, 15, 30};  List<Integer> res = intersection(a, b);  for (int x : res) {  System.out.print(x + " ");  }  } } 
Python
# Function to find the intersection of two arrays # It returns a list containing the common elements def intersection(a, b): res = [] m = len(a) n = len(b) for i in range(m): # Note that duplicates must be  # consecutive in a sorted array if i > 0 and a[i - 1] == a[i]: continue # Since we are only searching distinct # elements of a[] in b[] and we break as  # soon we find a match, we get only # distinct elements in result for j in range(n): if a[i] == b[j]: res.append(a[i]) break return res # Driver code a = [3, 5, 10, 10, 10, 15, 15, 20] b = [5, 10, 10, 15, 30] res = intersection(a, b) print(" ".join(map(str, res))) 
C#
using System; using System.Collections.Generic; class GfG {  // Function to find the intersection of two arrays  // It returns a list containing the common elements  static List<int> Intersection(int[] a, int[] b)  {  List<int> res = new List<int>();  int m = a.Length;  int n = b.Length;  for (int i = 0; i < m; i++)  {  // Note that duplicates must be   // consecutive in a sorted array  if (i > 0 && a[i - 1] == a[i])  continue;  // Since we are only searching distinct  // elements of a[] in b[] and we break as   // soon we find a match, we get only  // distinct elements in result  for (int j = 0; j < n; j++)  {  if (a[i] == b[j])  {  res.Add(a[i]);  break;  }  }  }  return res;  }  static void Main()  {  int[] a = { 3, 5, 10, 10, 10, 15, 15, 20 };  int[] b = { 5, 10, 10, 15, 30 };  List<int> res = Intersection(a, b);  foreach (int x in res)  {  Console.Write(x + " ");  }  } } 
JavaScript
// Function to find the intersection of two arrays // It returns an array containing the common elements function intersection(a, b) {  let res = [];  let m = a.length;  let n = b.length;  for (let i = 0; i < m; i++) {    // Note that duplicates must be   // consecutive in a sorted array  if (i > 0 && a[i - 1] === a[i]) {  continue;  }  // Since we are only searching distinct  // elements of a[] in b[] and we break as   // soon we find a match, we get only  // distinct elements in result  for (let j = 0; j < n; j++) {  if (a[i] === b[j]) {  res.push(a[i]);  break;  }  }  }  return res; } // Driver code let a = [3, 5, 10, 10, 10, 15, 15, 20]; let b = [5, 10, 10, 15, 30]; let res = intersection(a, b); console.log(res.join(" ")); 

Output
5 10 15 

Approaches Same as Unsorted Arrays - Best Time O(n+m) and O(n) Space

We have discussed different approaches for intersection of unsorted arrays. We can use the same approaches here. The best performance that we can achieve using the same approaches is O(n+m) Time and O(n) Auxiliary Space for hash set. Please note that in these approaches we do not use the fact that input arrays are sorted.

[Expected Approach] Using Merge Step of Merge Sort - O(n+m) Time and O(1) Space

The idea is based one merge function to merge two sorted arrays.

  1. We simultaneously traverse both a[] and b[] from the left side. While traversing, we avoid duplicates in a[]. We do not need to do it for b[] because once we have a match, we move ahead in a[] and b[] both.
  2. If current elements are not same, we skip the smaller of the two. If current element of a[] is smaller, we move ahead in a[] and if current of b[] is smaller, we move ahead in b[].
  3. Else (If same), we add one occurrence of the current element to the result and move ahead in both a[] and b[].


C++
#include <bits/stdc++.h> using namespace std; vector<int> intersection(vector<int>& a, vector<int>& b) {  vector<int> res;   int m = a.size();  int n = b.size();    // This is similar to merge of merge sort  int i = 0, j = 0;   while(i < m && j < n) {    // Skip duplicate elements in the first array  if(i > 0 && a[i - 1] == a[i]) {  i++;  continue;  }    // Skip the smaller  if(a[i] < b[j]) {  i++;  }  else if(a[i] > b[j]) {  j++;  }    // If equal, add to result and move both   else {  res.push_back(a[i]);  i++;  j++;  }  }  return res;  } int main() {  vector<int> a = {3, 5, 10, 10, 10, 15, 15, 20};  vector<int> b = {5, 10, 10, 15, 30};  vector<int> res = intersection(a, b);  for (int x : res) {  cout << x << " ";  } } 
C
#include <stdio.h> // Function to find the intersection of two arrays void intersection(int a[], int m, int b[], int n, int res[], int *res_size) {  int i = 0, j = 0;  // This is similar to merge of merge sort  while (i < m && j < n) {  // Skip duplicate elements in the first array  if (i > 0 && a[i - 1] == a[i]) {  i++;  continue;  }  // Skip the smaller  if (a[i] < b[j]) {  i++;  } else if (a[i] > b[j]) {  j++;  }  // If equal, add to result and move both  else {  res[(*res_size)++] = a[i];  i++;  j++;  }  } } int main() {  int a[] = {3, 5, 10, 10, 10, 15, 15, 20};  int b[] = {5, 10, 10, 15, 30};  int res[10];  int res_size = 0;  // Correctly call the intersection function  intersection(a, 8, b, 5, res, &res_size);  for (int i = 0; i < res_size; i++) {  printf("%d ", res[i]);  }  return 0; } 
Java
import java.util.ArrayList; import java.util.List; class GfG {  // Function to find the intersection of two arrays  static List<Integer> intersection(int[] a, int[] b) {  List<Integer> res = new ArrayList<>();  int m = a.length;  int n = b.length;  // This is similar to merge of merge sort  int i = 0, j = 0;  while (i < m && j < n) {  // Skip duplicate elements in the first array  if (i > 0 && a[i - 1] == a[i]) {  i++;  continue;  }  // Skip the smaller  if (a[i] < b[j]) {  i++;  } else if (a[i] > b[j]) {  j++;  }  // If equal, add to result and move both  else {  res.add(a[i]);  i++;  j++;  }  }  return res;  }  public static void main(String[] args) {  int[] a = {3, 5, 10, 10, 10, 15, 15, 20};  int[] b = {5, 10, 10, 15, 30};  List<Integer> res = intersection(a, b);  for (int x : res) {  System.out.print(x + " ");  }  } } 
Python
# Function to find the intersection of two arrays def intersection(a, b): res = [] m = len(a) n = len(b) # This is similar to merge of merge sort i, j = 0, 0 while i < m and j < n: # Skip duplicate elements in the first array if i > 0 and a[i - 1] == a[i]: i += 1 continue # Skip the smaller if a[i] < b[j]: i += 1 elif a[i] > b[j]: j += 1 # If equal, add to result and move both else: res.append(a[i]) i += 1 j += 1 return res # Driver code a = [3, 5, 10, 10, 10, 15, 15, 20] b = [5, 10, 10, 15, 30] res = intersection(a, b) print(" ".join(map(str, res))) 
C#
using System; using System.Collections.Generic; class GfG {  // Function to find the intersection of two arrays  static List<int> Intersection(int[] a, int[] b)  {  List<int> res = new List<int>();  int m = a.Length;  int n = b.Length;  // This is similar to merge of merge sort  int i = 0, j = 0;  while (i < m && j < n)  {  // Skip duplicate elements in the first array  if (i > 0 && a[i - 1] == a[i])  {  i++;  continue;  }  // Skip the smaller  if (a[i] < b[j])  {  i++;  }  else if (a[i] > b[j])  {  j++;  }  // If equal, add to result and move both  else  {  res.Add(a[i]);  i++;  j++;  }  }  return res;  }  static void Main()  {  int[] a = { 3, 5, 10, 10, 10, 15, 15, 20 };  int[] b = { 5, 10, 10, 15, 30 };  List<int> res = Intersection(a, b);  foreach (int x in res)  {  Console.Write(x + " ");  }  } } 
JavaScript
// Function to find the intersection of two arrays function intersection(a, b) {  let res = [];  let m = a.length;  let n = b.length;  // This is similar to merge of merge sort  let i = 0, j = 0;  while (i < m && j < n) {  // Skip duplicate elements in the first array  if (i > 0 && a[i - 1] === a[i]) {  i++;  continue;  }  // Skip the smaller  if (a[i] < b[j]) {  i++;  } else if (a[i] > b[j]) {  j++;  }  // If equal, add to result and move both  else {  res.push(a[i]);  i++;  j++;  }  }  return res; } // Driver code let a = [3, 5, 10, 10, 10, 15, 15, 20]; let b = [5, 10, 10, 15, 30]; let res = intersection(a, b); console.log(res.join(" ")); 

Output
5 10 15 

Time Complexity: O(n+m), where n and m is the size of a[] and b[] respectively.
Auxiliary Space: O(1)

Related Articles:


Similar Reads