Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Merge two sorted arrays
Next article icon

Intersection of Two Sorted Arrays

Last Updated : 11 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

Table of Content

  • [Naive Approach] Using Nested Loops - O(n*m) Time and O(1) Space
  • Approaches Same as Unsorted Arrays - Best Time O(n+m) and O(n) Space
  • [Expected Approach] Using Merge Step of Merge Sort - O(n+m) Time and O(1) Space

[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:

  • Intersection of Two Arrays
  • Intersection of Two Arrays with Distinct Elements
  • Intersection of Two Sorted Arrays with Distinct Elements
  • Union and Intersection of Two Unsorted Arrays
  • Union and Intersection of Two Sorted Arrays

Next Article
Merge two sorted arrays
author
kartik
Improve
Article Tags :
  • Searching
  • DSA
  • Arrays
  • Merge Sort
  • array-merge
  • union-intersection
Practice Tags :
  • Arrays
  • Merge Sort
  • Searching

Similar Reads

  • Intersection of two Arrays
    Given two arrays a[] and b[], the task is find 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 any order. Input: a[] = {1, 2, 1, 3, 1}, b[] =
    12 min read
  • Merge two sorted arrays
    Given two sorted arrays, the task is to merge them in a sorted manner.Examples: Input: arr1[] = { 1, 3, 4, 5}, arr2[] = {2, 4, 6, 8} Output: arr3[] = {1, 2, 3, 4, 4, 5, 6, 8} Input: arr1[] = { 5, 8, 9}, arr2[] = {4, 7, 8} Output: arr3[] = {4, 5, 7, 8, 8, 9} Table of Content [Naive Approach] Concaten
    10 min read
  • Intersection of Two Sorted Arrays with Distinct Elements
    Given two sorted arrays a[] and b[] with distinct elements of size n and m respectively, the task is to find intersection (or common elements) of the two arrays. We need to return the intersection in sorted order. Note: Intersection of two arrays can be defined as a set containing distinct common el
    13 min read
  • K-th Element of Merged Two Sorted Arrays
    Given two sorted arrays of sizes m and n respectively, the task is to find the element that would be at the k-th position in the final sorted array formed by merging these two arrays. Examples: Input: a[] = [2, 3, 6, 7, 9], b[] = [1, 4, 8, 10], k = 5Output: 6Explanation: The final sorted array is [1
    15+ min read
  • Median of two Sorted Arrays of Different Sizes
    Given two sorted arrays, a[] and b[], the task is to find the median of these sorted arrays. Assume that the two sorted arrays are merged and then median is selected from the combined array. This is an extension of Median of two sorted arrays of equal size problem. Here we handle arrays of unequal s
    15+ min read
  • Union and Intersection of Two Sorted Arrays - Complete Tutorial
    Union of two arrays is an array having all distinct elements that are present in either array whereas Intersection of two arrays is an array containing distinct common elements between the two arrays. In this post, we will discuss about Union and Intersection of sorted arrays. To know about union an
    6 min read
  • Sorted merge in one array
    Given two sorted arrays, A and B, where A has a large enough buffer at the end to hold B. Merge B into A in sorted order. Examples: Input : a[] = {10, 12, 13, 14, 18, NA, NA, NA, NA, NA} b[] = {16, 17, 19, 20, 22};; Output : a[] = {10, 12, 13, 14, 16, 17, 18, 19, 20, 22} One way is to merge the two
    7 min read
  • Symmetric difference of two sorted array
    There are two sorted array arr1 and arr2. We have to find the symmetric difference of Aarr1 and arr2. Symmetric Difference basically contains all elements of two arrays except common elements. Symmetric difference of two array is the all array elements of both array except the elements that are pres
    7 min read
  • Union of Two Sorted Arrays
    Given two sorted arrays a[] and b[], the task is to to return union of both the arrays in sorted order. Union of two arrays is an array having all distinct elements that are present in either array. The input arrays may contain duplicates. Examples: Input: a[] = {1, 1, 2, 2, 2, 4}, b[] = {2, 2, 4, 4
    15+ min read
  • Merging two unsorted arrays in sorted order
    Write a SortedMerge() function that takes two lists, each of which is unsorted, and merges the two together into one new list which is in sorted (increasing) order. SortedMerge() should return the new list. Examples : Input : a[] = {10, 5, 15} b[] = {20, 3, 2} Output : Merge List : {2, 3, 5, 10, 15,
    12 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences