Blog Logo

20 june 2025 ~ 1 min read

Find the intersection of two integer arrays 🛣️


Theory to get started

In this problem we take a best approach to use sets and store the data of one array in one set and another array in result set.

There are also other ways to solve this using hashmap or two pointers technique

Here is the breakdown of the steps in the code:

/* 
    Given two integer arrays nums1 and nums2, return 
    an array of their intersection. 
    Each element in the result must be unique and you 
    may return the result in any order.
*/
#include<stdio.h>
#include<vector>
#include<iostream>
#include <set>

using namespace std;

vector<int> getArrayIntersection(vector<int>& num1, vector<int>& num2){
    /* step1: store num1 into set */
    set<int> mySet;
    set<int> resultSet;
    for(int i=0; i<num1.size(); i++){
        mySet.insert(num1[i]);
    }
    /* step1: check if num2 is found in the set */
    for(int i=0; i<num2.size(); i++){
        if(mySet.find(num2[i]) != mySet.end()){
            resultSet.insert(num2[i]);
        }
    }
    /* step3: return resultSet that contains numbers
        that were found in num2 that exists in num1
    */
    return vector<int>(resultSet.begin(), resultSet.end());
}

int main(){

    vector<int> num1 = {1, 3, 2, 3};
    vector<int> num2 = {3,2};

    vector<int> ans = getArrayIntersection(num1, num2);
    for (auto &it : ans) {
        cout << it << " ";
    }
    return 0;
}

[Top]


Headshot of Dhruvjit

Hi, I'm Dhruvjit. I'm a software engineer based in India. You can follow me on Twitter, see some of my work on GitHub, or read more about me on my website.