- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Intersection of Two Arrays in C++
Suppose we have two arrays; we have to find their intersections.
So, if the input is like [1,5,3,6,9],[2,8,9,6,7], then the output will be [9,6]
To solve this, we will follow these steps −
Define two maps mp1, mp2
Define an array res
for x in nums1
(increase mp1[x] by 1)
for x in nums2
(increase mp2[x] by 1)
for each key-value pair x in mp1
cnt := 0
cnt := minimum of value of x and mp2[key of x]
if cnt > 0, then −
insert key of x at the end of res
return res
Example
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> intersection(vector<int>& nums1, vector<int>& nums2){ unordered_map<int, int> mp1, mp2; vector<int> res; for (auto x : nums1) mp1[x]++; for (auto x : nums2) mp2[x]++; for (auto x : mp1) { int cnt = 0; cnt = min(x.second, mp2[x.first]); if (cnt > 0) res.push_back(x.first); } return res; } }; main(){ Solution ob; vector<int> v = {1,5,3,6,9}, v1 = {2,8,9,6,7}; print_vector(ob.intersection(v, v1)); }
Input
{1,5,3,6,9},{2,8,9,6,7}
Output
[9, 6, ]
- Related Articles
- Intersection of two arrays in C#
- Intersection of two arrays in Java
- Intersection of two arrays JavaScript
- Intersection of Two Arrays II in Python
- Find Union and Intersection of two unsorted arrays in C++
- C program to perform intersection operation on two arrays
- Intersection of Three Sorted Arrays in C++
- C++ program to find union and intersection of two unsorted arrays
- How to get the intersection of two arrays in MongoDB?
- How to find the intersection of two arrays in java?
- How to find intersection between two Numpy arrays?
- Unique intersection of arrays in JavaScript
- Intersection of two HashSets in C#
- The intersection of two arrays in Python (Lambda expression and filter function )
- Intersection of three sorted arrays in JavaScript

Advertisements