Arrays January 13 ,2026

Find Intersection of Two Arrays

Problem Statement

Given two arrays, find their intersection.

The intersection of two arrays consists of:

  • Elements that are present in both arrays
  • Each common element should appear only once in the result, even if it appears multiple times in the input arrays

The order of elements is not important unless explicitly mentioned.

Example 1

Input

arr1 = [1, 2, 3, 4]
arr2 = [3, 4, 5, 6]

Output

[3, 4]

Example 2

Input

arr1 = [1, 2, 2, 3]
arr2 = [2, 2, 4]

Output

[2]

Why This Problem Is Important

This is a frequently asked array interview problem because it:

  • Tests understanding of duplicate handling
  • Introduces hashing and set concepts
  • Helps build logic for:
    • Set operations
    • Data filtering
    • Comparing datasets

This problem also acts as a foundation for:

  • Union of arrays
  • Difference of arrays
  • Symmetric difference problems

Approaches to Solve the Problem

  1. Brute Force Approach
  2. Using Hashing (Best and Most Efficient)
  3. Sorting + Two Pointers (For Sorted Arrays)

Approach 1: Brute Force Method

Idea

  • Compare each element of the first array with every element of the second array
  • If elements match, add them to the result
  • Ensure duplicates are not added more than once

Algorithm

  1. Create an empty result array
  2. Loop through arr1
  3. For each element in arr1, loop through arr2
  4. If elements are equal:
    • Check if the element already exists in result
    • Add it if not present
  5. Print the result array

Time and Space Complexity

  • Time Complexity: O(n × m)
  • Space Complexity: O(k)
    (where k is the number of common elements)

C Implementation

#include<stdio.h> 

int main() {
    int arr1[] = {1, 2, 2, 3};
    int arr2[] = {2, 2, 4};
    int n1 = 4, n2 = 3;

    int result[10];
    int k = 0;

    for (int i = 0; i < n1; i++) {
        for (int j = 0; j < n2; j++) {
            if (arr1[i] == arr2[j]) {

                int found = 0;
                for (int x = 0; x < k; x++) {
                    if (result[x] == arr1[i]) {
                        found = 1;
                        break;
                    }
                }

                if (!found) {
                    result[k++] = arr1[i];
                }
            }
        }
    }

    printf("Intersection: ");
    for (int i = 0; i < k; i++)
        printf("%d ", result[i]);

    return 0;
}

C++ Implementation

#include<iostream> 
using namespace std;

int main() {
    int arr1[] = {1, 2, 2, 3};
    int arr2[] = {2, 2, 4};
    int n1 = 4, n2 = 3;

    int result[10];
    int k = 0;

    for (int i = 0; i < n1; i++) {
        for (int j = 0; j < n2; j++) {
            if (arr1[i] == arr2[j]) {

                bool found = false;
                for (int x = 0; x < k; x++) {
                    if (result[x] == arr1[i]) {
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    result[k++] = arr1[i];
                }
            }
        }
    }

    cout << "Intersection: ";
    for (int i = 0; i < k; i++)
        cout << result[i] << " ";

    return 0;
}

Java Implementation

public class IntersectionBruteForce {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 2, 3};
        int[] arr2 = {2, 2, 4};

        int[] result = new int[10];
        int k = 0;

        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr2.length; j++) {
                if (arr1[i] == arr2[j]) {

                    boolean found = false;
                    for (int x = 0; x < k; x++) {
                        if (result[x] == arr1[i]) {
                            found = true;
                            break;
                        }
                    }

                    if (!found) {
                        result[k++] = arr1[i];
                    }
                }
            }
        }

        System.out.print("Intersection: ");
        for (int i = 0; i < k; i++)
            System.out.print(result[i] + " ");
    }
}

Python Implementation

arr1 = [1, 2, 2, 3]
arr2 = [2, 2, 4]

result = []

for i in arr1:
    for j in arr2:
        if i == j and i not in result:
            result.append(i)

print("Intersection:", result)

JavaScript Implementation

let arr1 = [1, 2, 2, 3];
let arr2 = [2, 2, 4];

let result = [];

for (let i = 0; i < arr1.length; i++) {
    for (let j = 0; j < arr2.length; j++) {
        if (arr1[i] === arr2[j] && !result.includes(arr1[i])) {
            result.push(arr1[i]);
        }
    }
}

console.log("Intersection:", result);
Find the intersection of two unsorted arrays - Interview Problem

Idea

  • Store elements of the first array in a hash set
  • Traverse the second array
  • If an element exists in the set:
    • Add it to the result
    • Remove it from the set to avoid duplicates

Algorithm

  1. Insert all elements of arr1 into a hash set
  2. Traverse arr2
  3. If current element exists in the set:
    • Print or store it
    • Remove it from the set

Time and Space Complexity

  • Time Complexity: O(n + m)
  • Space Complexity: O(n)

C++ Implementation

#include<iostream> 
#include<unordered_set> 
using namespace std;

int main() {
    int arr1[] = {1, 2, 3, 4};
    int arr2[] = {3, 4, 5, 6};

    unordered_set s(arr1, arr1 + 4);

    cout << "Intersection: ";
    for (int x : arr2) {
        if (s.find(x) != s.end()) {
            cout << x << " ";
            s.erase(x);
        }
    }
    return 0;
}

Output

Intersection: 3 4

Java Implementation

import java.util.*;

public class IntersectionArray {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 3, 4};
        int[] arr2 = {3, 4, 5, 6};

        Set set = new HashSet<>();
        for (int x : arr1)
            set.add(x);

        Set result = new HashSet<>();
        for (int x : arr2) {
            if (set.contains(x))
                result.add(x);
        }

        System.out.println("Intersection: " + result);
    }
}

Output

Intersection: [3, 4]

Python Implementation

arr1 = [1, 2, 3, 4]
arr2 = [3, 4, 5, 6]

intersection = list(set(arr1) & set(arr2))
print("Intersection:", intersection)

Output

Intersection: [3, 4]

JavaScript Implementation

let arr1 = [1, 2, 3, 4];
let arr2 = [3, 4, 5, 6];

let set1 = new Set(arr1);
let result = [];

for (let x of arr2) {
    if (set1.has(x)) {
        result.push(x);
        set1.delete(x);
    }
}

console.log("Intersection:", result);

Output

Intersection: [3, 4]

Approach 3: Sorting + Two Pointers (For Sorted Arrays)

Idea

  • Sort both arrays
  • Use two pointers to compare elements
  • Move pointers based on comparison
  • Skip duplicates

Time and Space Complexity

  • Time Complexity: O(n log n + m log m)
  • Space Complexity: O(1) (excluding output)

Approach 3: Sorting + Two Pointers

C Implementation

#include<stdio.h> 

int main() {
    int arr1[] = {1, 2, 2, 3};
    int arr2[] = {2, 2, 4};
    int n1 = 4, n2 = 3;

    // Sort arr1
    for (int i = 0; i < n1 - 1; i++) {
        for (int j = i + 1; j < n1; j++) {
            if (arr1[i] > arr1[j]) {
                int temp = arr1[i];
                arr1[i] = arr1[j];
                arr1[j] = temp;
            }
        }
    }

    // Sort arr2
    for (int i = 0; i < n2 - 1; i++) {
        for (int j = i + 1; j < n2; j++) {
            if (arr2[i] > arr2[j]) {
                int temp = arr2[i];
                arr2[i] = arr2[j];
                arr2[j] = temp;
            }
        }
    }

    int i = 0, j = 0;
    int lastPrinted = -1;

    printf("Intersection: ");
    while (i < n1 && j < n2) {
        if (arr1[i] == arr2[j]) {
            if (arr1[i] != lastPrinted) {
                printf("%d ", arr1[i]);
                lastPrinted = arr1[i];
            }
            i++;
            j++;
        } else if (arr1[i] < arr2[j]) {
            i++;
        } else {
            j++;
        }
    }

    return 0;
}

C++ Implementation

#include<iostream> 
#include <algorithm>
using namespace std;

int main() {
    int arr1[] = {1, 2, 2, 3};
    int arr2[] = {2, 2, 4};
    int n1 = 4, n2 = 3;

    sort(arr1, arr1 + n1);
    sort(arr2, arr2 + n2);

    int i = 0, j = 0;
    int lastPrinted = -1;

    cout << "Intersection: ";
    while (i < n1 && j < n2) {
        if (arr1[i] == arr2[j]) {
            if (arr1[i] != lastPrinted) {
                cout << arr1[i] << " ";
                lastPrinted = arr1[i];
            }
            i++;
            j++;
        } else if (arr1[i] < arr2[j]) {
            i++;
        } else {
            j++;
        }
    }

    return 0;
}

Java Implementation

import java.util.Arrays;

public class IntersectionTwoPointers {
    public static void main(String[] args) {
        int[] arr1 = {1, 2, 2, 3};
        int[] arr2 = {2, 2, 4};

        Arrays.sort(arr1);
        Arrays.sort(arr2);

        int i = 0, j = 0;
        Integer lastPrinted = null;

        System.out.print("Intersection: ");
        while (i < arr1.length && j < arr2.length) {
            if (arr1[i] == arr2[j]) {
                if (lastPrinted == null || arr1[i] != lastPrinted) {
                    System.out.print(arr1[i] + " ");
                    lastPrinted = arr1[i];
                }
                i++;
                j++;
            } else if (arr1[i] < arr2[j]) {
                i++;
            } else {
                j++;
            }
        }
    }
}

Python Implementation

arr1 = [1, 2, 2, 3]
arr2 = [2, 2, 4]

arr1.sort()
arr2.sort()

i = j = 0
result = []

while i < len(arr1) and j < len(arr2):
    if arr1[i] == arr2[j]:
        if not result or result[-1] != arr1[i]:
            result.append(arr1[i])
        i += 1
        j += 1
    elif arr1[i] < arr2[j]:
        i += 1
    else:
        j += 1

print("Intersection:", result)

JavaScript Implementation

let arr1 = [1, 2, 2, 3];
let arr2 = [2, 2, 4];

arr1.sort((a, b) => a - b);
arr2.sort((a, b) => a - b);

let i = 0, j = 0;
let result = [];

while (i < arr1.length && j < arr2.length) {
    if (arr1[i] === arr2[j]) {
        if (result.length === 0 || result[result.length - 1] !== arr1[i]) {
            result.push(arr1[i]);
        }
        i++;
        j++;
    } else if (arr1[i] < arr2[j]) {
        i++;
    } else {
        j++;
    }
}

console.log("Intersection:", result);

Summary

  • Intersection includes only common elements
  • Each element appears once
  • Hashing provides the best performance
  • Order is not guaranteed unless sorted

Key Takeaways

  • Best Time Complexity: O(n + m)
  • Avoid duplicates using sets
  • Suitable for interview and real-world use cases

Next Problem in the Series

Sort an Array of 0s and 1s


 

Sanjiv
0

You must logged in to post comments.

Related Blogs

Find the S...
Arrays February 02 ,2026

Find the Second Smal...

Find the S...
Arrays January 01 ,2026

Find the Sum of All...

Find the M...
Arrays January 01 ,2026

Find the Maximum Ele...

Find the M...
Arrays January 01 ,2026

Find the Minimum Ele...

Count Even...
Arrays January 01 ,2026

Count Even and Odd N...

Search an...
Arrays January 01 ,2026

Search an Element in...

Copy One A...
Arrays January 01 ,2026

Copy One Array into...

Reverse an...
Arrays January 01 ,2026

Reverse an Array

Print Alte...
Arrays January 01 ,2026

Print Alternate Elem...

Find the L...
Arrays January 01 ,2026

Find the Length of a...

Check if a...
Arrays January 01 ,2026

Check if an Array is...

Find the F...
Arrays January 01 ,2026

Find the First Eleme...

Find the L...
Arrays January 01 ,2026

Find the Last Elemen...

Count the...
Arrays January 01 ,2026

Count the Number of...

Replace Al...
Arrays January 01 ,2026

Replace All Elements...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at E...

Sum of Ele...
Arrays January 01 ,2026

Sum of Elements at O...

Find the A...
Arrays January 01 ,2026

Find the Average of...

Count the...
Arrays January 01 ,2026

Count the Number of...

Remove Dup...
Arrays January 01 ,2026

Remove Duplicate Ele...

Move All Z...
Arrays January 01 ,2026

Move All Zeros to th...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by K...

Rotate an...
Arrays January 01 ,2026

Rotate an Array by O...

Check if T...
Arrays January 01 ,2026

Check if Two Arrays...

Merge Two...
Arrays January 01 ,2026

Merge Two Sorted Arr...

Find Missi...
Arrays January 01 ,2026

Find Missing Number...

Find Dupli...
Arrays January 01 ,2026

Find Duplicate Eleme...

Count Freq...
Arrays January 01 ,2026

Count Frequency of E...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All U...
Arrays January 01 ,2026

Find All Unique Elem...

Insert an...
Arrays January 01 ,2026

Insert an Element at...

Delete an...
Arrays January 01 ,2026

Delete an Element fr...

Find the I...
Arrays January 01 ,2026

Find the Index of an...

Find Union...
Arrays January 01 ,2026

Find Union of Two Ar...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s...

Find the L...
Arrays January 01 ,2026

Find the Largest Sum...

Kadane’s A...
Arrays January 01 ,2026

Kadane’s Algorithm (...

Two Sum Pr...
Arrays January 01 ,2026

Two Sum Problem

Subarray w...
Arrays January 01 ,2026

Subarray with Given...

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Rearrange...
Arrays January 01 ,2026

Rearrange Array Alte...

Leaders in...
Arrays January 01 ,2026

Leaders in an Array

Equilibriu...
Arrays January 01 ,2026

Equilibrium Index of...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Stock Buy...
Arrays January 01 ,2026

Stock Buy and Sell (...

Sort an Ar...
Arrays January 01 ,2026

Sort an Array of 0s,...

Find the M...
Arrays January 01 ,2026

Find the Majority El...

Find All P...
Arrays January 01 ,2026

Find All Pairs with...

Longest Co...
Arrays January 01 ,2026

Longest Consecutive...

Product of...
Arrays January 01 ,2026

Product of Array Exc...

Maximum Pr...
Arrays January 01 ,2026

Maximum Product Suba...

Find the F...
Arrays January 01 ,2026

Find the First Missi...

Count Inve...
Arrays January 01 ,2026

Count Inversions in...

Rearrange...
Arrays January 01 ,2026

Rearrange Array by S...

Check if A...
Arrays January 01 ,2026

Check if Array Can B...

Trapping R...
Arrays January 01 ,2026

Trapping Rain Water

Find Minim...
Arrays January 01 ,2026

Find Minimum in Rota...

Search in...
Arrays January 01 ,2026

Search in Rotated So...

Median of...
Arrays January 01 ,2026

Median of Two Sorted...

Merge Inte...
Arrays January 01 ,2026

Merge Intervals

Count Reve...
Arrays January 01 ,2026

Count Reverse Pairs

Longest Su...
Arrays January 01 ,2026

Longest Subarray wit...

Largest Re...
Arrays January 01 ,2026

Largest Rectangle in...

Maximum Su...
Arrays January 01 ,2026

Maximum Sum Rectangl...

Subarray S...
Arrays January 01 ,2026

Subarray Sum Equals...

Count Dist...
Arrays January 01 ,2026

Count Distinct Eleme...

Sliding Wi...
Arrays January 01 ,2026

Sliding Window Maxim...

Find K Max...
Arrays January 01 ,2026

Find K Maximum Eleme...

Minimum Nu...
Arrays January 01 ,2026

Minimum Number of Ju...

Chocolate...
Arrays January 01 ,2026

Chocolate Distributi...

Find All T...
Arrays January 01 ,2026

Find All Triplets Wi...

Kth Smalle...
Arrays January 01 ,2026

Kth Smallest Element...

Maximum Le...
Arrays January 01 ,2026

Maximum Length Biton...

Find the S...
Arrays February 02 ,2026

Find the Second Larg...

Get In Touch

Kurki bazar Uttar Pradesh

+91-8808946970

techiefreak87@gmail.com