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 Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Union of Two Arrays with Distinct Elements
Next article icon

Intersection of Two Arrays with Distinct Elements

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

Given two 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 can return the answer in any order.

Note: Intersection of two arrays can be defined as a set containing distinct common elements between the two arrays.

Examples:

Input: a[] = { 5, 6, 2, 1, 4 }, b[] = { 7, 9, 4, 2 }
Output: { 2, 4 }
Explanation: The only common elements in both arrays are 2 and 4.

Input: a[] = { 4, 5, 2, 3 } , b[] = { 1, 7 }
Output: { }
Explanation: There are no common elements in array a[] and b[]

Table of Content

  • [Naive Approach] Using nested loop - O(n*m) Time and O(1) Space
  • [Better Approach] Using Sorting and Two Pointers - O(n*logm) Time and O(1) Space
  • [Expected Approach] Using Hash Set - O(n+m) Time and O(n) Space

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

The idea is to traverse the first array a[] and for each element from a[], check whether it is present in array b[]. If present then add this element to result array.

C++
// C++ program for intersection of two arrays with // distinct elements using nested loops  #include <iostream> #include <vector> using namespace std;  vector<int> intersection(vector<int>& a, vector<int>& b) {     vector<int> res;      // Traverse through a[] and search every element     // a[i] in b[]     for (int i = 0; i < a.size(); i++) {          	for (int j = 0; j < b.size(); j++) {                        // If found in b[], then add this           	// element to result array             if (a[i] == b[j]) {                	res.push_back(a[i]);               	break;             }         }     }      return res; }  int main() {     vector<int> a = {5, 6, 2, 1, 4};      vector<int> b = {7, 9, 4, 2};      vector<int> res = intersection(a, b);        for (int i = 0; i < res.size(); i++)          cout << res[i] << " ";      return 0; } 
C
// C program for intersection of two arrays with // distinct elements using nested loops  #include <stdio.h>  int* intersection(int a[], int n, int b[], int m, int* resSize) {     int* res = (int*)malloc(100 * sizeof(int));      *resSize = 0;         	     for (int i = 0; i < n; i++) {         for (int j = 0; j < m; j++) {             if (a[i] == b[j]) {                 res[(*resSize)++] = a[i];                 break;             }         }     }      return res; }  int main() {     int a[] = {5, 6, 2, 1, 4};     int b[] = {7, 9, 4, 2};     int resSize;          int* res = intersection(a, 5, b, 4, &resSize);      for (int i = 0; i < resSize; i++) {         printf("%d ", res[i]);     }      return 0; } 
Java
// Java program for intersection of two arrays with // distinct elements using nested loops  import java.util.ArrayList;  class GfG {     static ArrayList<Integer> intersection(int[] a, int[] b) {         ArrayList<Integer> res = new ArrayList<>();          for (int i = 0; i < a.length; i++) {             for (int j = 0; j < b.length; j++) {                 if (a[i] == b[j]) {                     res.add(a[i]);                     break;                 }             }         }          return res;     }      public static void main(String[] args) {         int[] a = {5, 6, 2, 1, 4};         int[] b = {7, 9, 4, 2};          ArrayList<Integer> res = intersection(a, b);          for (int num : res) {             System.out.print(num + " ");         }     } } 
Python
# Python program for intersection of two arrays with # distinct elements using nested loops  def intersection(a, b):     res = []      for i in range(len(a)):         for j in range(len(b)):             if a[i] == b[j]:                 res.append(a[i])                 break      return res  if __name__ == "__main__":     a = [5, 6, 2, 1, 4]     b = [7, 9, 4, 2]      res = intersection(a, b)      for num in res:         print(num, end=" ") 
C#
// C# program for intersection of two arrays with // distinct elements using nested loops  using System; using System.Collections.Generic;  class GfG {     static List<int> intersection(int[] a, int[] b) {         List<int> res = new List<int>();          for (int i = 0; i < a.Length; i++) {             for (int j = 0; j < b.Length; j++) {                 if (a[i] == b[j]) {                     res.Add(a[i]);                     break;                 }             }         }          return res;     }      static void Main() {         int[] a = {5, 6, 2, 1, 4};         int[] b = {7, 9, 4, 2};          List<int> res = intersection(a, b);          foreach (int num in res) {             Console.Write(num + " ");         }     } } 
JavaScript
// JavaScript program for intersection of two arrays with // distinct elements using nested loops  function intersection(a, b) {     let res = [];      for (let i = 0; i < a.length; i++) {         for (let j = 0; j < b.length; j++) {             if (a[i] === b[j]) {                 res.push(a[i]);                 break;             }         }     }      return res; }  let a = [5, 6, 2, 1, 4]; let b = [7, 9, 4, 2];  let res = intersection(a, b);  console.log(res.join(" ")); 

Output
2 4 

Time Complexity : O(n*m), where n and m are size of array a[] and b[] respectively.
Auxiliary Space : O(1)

[Better Approach] Using Sorting and Two Pointers - O(n*logm) Time and O(1) Space

The idea is to sort both the arrays and then maintain a pointer at the beginning of each array. By comparing the elements at both pointers, we can decide how to proceed:

  • If the element in the first array is smaller than the one in the second, move the pointer in the first array forward, because that element can't be part of the intersection.
  • If the element in the first array is greater, move the second pointer forward.
  • If the two elements are equal, you add that element to the result and move both pointers forward.

This continues until one of the pointers reaches the end of its array.

To know more about the implementation of this approach, please refer the post Intersection of Two Sorted Arrays with Distinct Elements.

[Expected Approach] Using Hash Set - O(n+m) Time and O(n) Space

The idea is to use a hash set to store the elements of array a[]. Then, go through array b[] and check if each element is present in the hash set. If an element is found in the hash set, add it to the result array since it is common in both the arrays.

C++
// C++ program for intersection of two arrays with // distinct elements using hash set  #include <iostream> #include <vector> #include <unordered_set> using namespace std;  vector<int> intersect(vector<int>& a, vector<int>& b) {        // Put all elements of a[] in hash set     unordered_set<int> st(a.begin(), a.end());       vector<int> res;                                 for (int i = 0; i < b.size(); i++) {                // If the element is in st         // then add it to result array         if (st.find(b[i]) != st.end()) {             res.push_back(b[i]);          }     }      return res; }  int main() {     vector<int> a = {5, 6, 2, 1, 4};      vector<int> b = {7, 9, 4, 2};      vector<int> res = intersect(a, b);     for (int i = 0; i < res.size(); i++)          cout << res[i] << " ";      return 0; } 
Java
// Java program for intersection of two arrays with // distinct elements using hash set  import java.util.*;  class GfG {     static ArrayList<Integer> intersect(int[] a, int[] b) {       	         // Put all elements of a[] in hash set         HashSet<Integer> st = new HashSet<>();         for (int num : a) {             st.add(num);         }         ArrayList<Integer> res = new ArrayList<>();         for (int i = 0; i < b.length; i++) {                        // If the element is in st             // then add it to result array             if (st.contains(b[i])) {                 res.add(b[i]);             }         }          return res;     }      public static void main(String[] args) {         int[] a = {5, 6, 2, 1, 4};         int[] b = {7, 9, 4, 2};          ArrayList<Integer> res = intersect(a, b);         for (int num : res) {             System.out.print(num + " ");         }     } } 
Python
# Python program for intersection of two arrays with # distinct elements using hash set  def intersect(a, b):        # Put all elements of a[] in hash set     st = set(a)     res = []     for i in range(len(b)):                # If the element is in st         # then add it to result array         if b[i] in st:             res.append(b[i])      return res  if __name__ == "__main__":     a = [5, 6, 2, 1, 4]     b = [7, 9, 4, 2]      res = intersect(a, b)     for num in res:         print(num, end=" ") 
C#
// C# program for intersection of two arrays with // distinct elements using hash set  using System; using System.Collections.Generic;  class GfG {     static List<int> intersect(int[] a, int[] b) {                // Put all elements of a[] in hash set         HashSet<int> st = new HashSet<int>(a);         List<int> res = new List<int>();         for (int i = 0; i < b.Length; i++) {                        // If the element is in st             // then add it to result array             if (st.Contains(b[i])) {                 res.Add(b[i]);             }         }          return res;     }      static void Main() {         int[] a = {5, 6, 2, 1, 4};         int[] b = {7, 9, 4, 2};          List<int> res = intersect(a, b);         foreach (int num in res) {             Console.Write(num + " ");         }     } } 
JavaScript
// JavaScript program for intersection of two arrays with // distinct elements using hash set  function intersect(a, b) {        // Put all elements of a[] in hash set     let st = new Set(a);     let res = [];     for (let i = 0; i < b.length; i++) {                // If the element is in st         // then add it to result array         if (st.has(b[i])) {             res.push(b[i]);         }     }      return res; }  let a = [5, 6, 2, 1, 4]; let b = [7, 9, 4, 2];  let res = intersect(a, b); console.log(res.join(" ")); 

Output
4 2 

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

Related Articles:

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

Next Article
Union of Two Arrays with Distinct Elements

A

anugum2xzm
Improve
Article Tags :
  • Hash
  • C++
  • DSA
  • Arrays
  • union-intersection
Practice Tags :
  • CPP
  • Arrays
  • Hash

Similar Reads

  • 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
  • Union of Two Arrays with Distinct Elements
    Given two arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in any order. Note: Union of two arrays is an array having all distinct elements that are present in either array. Examples: Input: a[] = {1, 2, 3}, b[] = {5, 2, 7}Output: {1, 2, 3, 5, 7}Explanation:
    7 min read
  • Union of Two Sorted Arrays with Distinct Elements
    Given two sorted arrays a[] and b[] with distinct elements, the task is to return union of both the arrays in sorted order. Note: Union of two arrays is an array having all distinct elements that are present in either array. Examples: Input: a[] = {1, 2, 3}, b[] = {2, 5, 7}Output: {1, 2, 3, 5, 7}Exp
    15+ min read
  • 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
  • JavaScript Program to Print All Distinct Elements in an Integer Array
    Given an Array of Integers consisting of n elements with repeated elements, the task is to print all the distinct elements of the array using JavaScript. We can get the distinct elements by creating a set from the integer array. Examples: Input : arr = [ 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9 ] Outpu
    3 min read
  • Count distinct elements in an array in Python
    Given an unsorted array, count all distinct elements in it. Examples: Input : arr[] = {10, 20, 20, 10, 30, 10} Output : 3 Input : arr[] = {10, 20, 20, 10, 20} Output : 2 We have existing solution for this article. We can solve this problem in Python3 using Counter method. Approach#1: Using Set() Thi
    2 min read
  • intersection_update() in Python to find common elements in n arrays
    We are given list of n number of arrays, find all common elements in given arrays ? Examples: Input : arr = [[1,2,3,4], [8,7,3,2], [9,2,6,3], [5,1,2,3]] Output : Common Elements = [2,3] We can solve this problem quickly in python using intersection_update() method of Set() data structure. How inters
    1 min read
  • Print all Distinct (Unique) Elements in given Array
    Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
    11 min read
  • Find distinct elements common to all rows of a matrix
    Given a n x n matrix. The problem is to find all the distinct elements common to all rows of the matrix. The elements can be printed in any order. Examples: Input : mat[][] = { {2, 1, 4, 3}, {1, 2, 3, 2}, {3, 6, 2, 3}, {5, 2, 5, 3} } Output : 2 3 Input : mat[][] = { {12, 1, 14, 3, 16}, {14, 2, 1, 3,
    15+ min read
  • Minimum Subsets with Distinct Elements
    You are given an array of n-element. You have to make subsets from the array such that no subset contain duplicate elements. Find out minimum number of subset possible. Examples : Input : arr[] = {1, 2, 3, 4}Output :1Explanation : A single subset can contains all values and all values are distinct.I
    9 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