Common Elements in Two Arrays (original) (raw)

Last Updated : 23 Jul, 2025

Given two arrays, the task is find common elements of the two arrays. The input arrays may contain duplicates and our job is to find all common elements We are allowed to return elements in any order.

**Input : a[] = {1, 2, 1, 3, 1}, b[] = {3, 1, 3, 4, 1}
**Output : {1, 3, 1}
1 appears two times in both the input arrays.

**Input : a[] = {1, 1, 1}, b[] = {1, 1, 1, 1, 1}
**Output : {1, 1, 1}
1 appears three times in both the input arrays.

**Input : a[] = {1, 2, 3}, b[] = {4, 5, 6}
**Output : {}

Try It Yourselfredirect icon

Table of Content

Naive Approach - O(n*m) Time and O(1) Space

  1. Initialize an empty array **res[] to store result
  2. Traverse through a[] and for every element check if it is in **b[]. If we find in **b[] also, then add it to the result. Also, mark the current element of **b[] as visited using a separate boolean array. We need visited array because we search the whole b[] for every **a[i].
  3. Return res[] C++ `

#include #include using namespace std;

vector findCommon(vector& a, vector& b) { vector res; vector visited(b.size(), false);

// For every element in a[] check if we have
// matching not yet visited element in b[].
// If yes, add the item to result.
for (int i = 0; i < a.size(); i++) {
    for (int j = 0; j < b.size(); j++) {
        if (a[i] == b[j] && !visited[j]) {
            res.push_back(a[i]);
            visited[j] = true;  
            break;
        }
    }
}
return res;

}

int main() { vector a = {1, 2, 1, 3, 1}; vector b = {3, 1, 3, 4, 1};

vector<int> result = findCommon(a, b);

for (int x : result) {
    cout << x << " ";
}
return 0;

}

C

#include <stdio.h> #include <stdbool.h>

void findCommon(int a[], int sizeA, int b[], int sizeB, int res[], int *res_size) { bool visited[sizeB];

// Initialize visited array with false
for (int i = 0; i < sizeB; i++) {
    visited[i] = false;
}

// For every element in a[] check if we have
// matching not yet visited element in b[].
// If yes, add the item to result.
for (int i = 0; i < sizeA; i++) {
    for (int j = 0; j < sizeB; j++) {
        if (a[i] == b[j] && !visited[j]) {
            res[(*res_size)++] = a[i];
            visited[j] = true;  
            break;
        }
    }
}

}

int main() { int a[] = {1, 2, 1, 3, 1}; int b[] = {3, 1, 3, 4, 1}; int res[5]; int res_size = 0;

findCommon(a, 5, 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 {

static List<Integer> findCommon(int[] a, int[] b) {
    List<Integer> res = new ArrayList<>();
    boolean[] visited = new boolean[b.length];
    
    // For every element in a[] check if we have
    // matching not yet visited element in b[].
    // If yes, add the item to result.
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < b.length; j++) {
            if (a[i] == b[j] && !visited[j]) {
                res.add(a[i]);
                visited[j] = true;
                break;
            }
        }
    }
    return res;
}

public static void main(String[] args) {
    int[] a = {1, 2, 1, 3, 1};
    int[] b = {3, 1, 3, 4, 1};

    List<Integer> result = findCommon(a, b);

    for (int x : result) {
        System.out.print(x + " ");
    }
}

}

Python

def findCommon(a, b): res = [] visited = [False] * len(b)

# For every element in a[] check if we have
# matching not yet visited element in b[].
# If yes, add the item to result.
for i in range(len(a)):
    for j in range(len(b)):
        if a[i] == b[j] and not visited[j]:
            res.append(a[i])
            visited[j] = True
            break
return res

Driver code

a = [1, 2, 1, 3, 1] b = [3, 1, 3, 4, 1]

result = findCommon(a, b)

print(" ".join(map(str, result)))

C#

using System; using System.Collections.Generic;

class GfG { static List findCommon(int[] a, int[] b) { List res = new List(); bool[] visited = new bool[b.Length];

    // For every element in a[] check if we have
    // matching not yet visited element in b[].
    // If yes, add the item to result.
    for (int i = 0; i < a.Length; i++) {
        for (int j = 0; j < b.Length; j++) {
            if (a[i] == b[j] && !visited[j]) {
                res.Add(a[i]);
                visited[j] = true;
                break;
            }
        }
    }
    return res;
}

static void Main() {
    int[] a = {1, 2, 1, 3, 1};
    int[] b = {3, 1, 3, 4, 1};

    List<int> result = findCommon(a, b);

    foreach (int x in result) {
        Console.Write(x + " ");
    }
}

}

JavaScript

function findCommon(a, b) { const res = []; const visited = new Array(b.length).fill(false);

// For every element in a[] check if we have
// matching not yet visited element in b[].
// If yes, add the item to result.
for (let i = 0; i < a.length; i++) {
    for (let j = 0; j < b.length; j++) {
        if (a[i] === b[j] && !visited[j]) {
            res.push(a[i]);
            visited[j] = true;
            break;
        }
    }
}
return res;

}

// Driver code const a = [1, 2, 1, 3, 1]; const b = [3, 1, 3, 4, 1];

const result = findCommon(a, b); console.log(result.join(" "));

`

Expected Approach - O(n + m) Time and O(n) Space

  1. Create a hash map **bm and store every item of **b[] as key and its frequency as value.
  2. Create an empty array **res[] to store result
  3. Traverse through all items of a[]. If an item is in the hash map **bm, then add it to **res[] and decrease its frequency by 1 in **bm.
  4. Return **res[] C++ `

#include #include #include using namespace std;

vector findCommon(vector& a, vector& b) {

// Store the frequency of elements in b[]
unordered_map<int, int> bm;  
for (int x : b) {
    bm[x]++;
}

// Traverse a[] and conisder an
// item as common only if its 
// frequency is more than 0 in bm.
vector<int> res;
for (int x : a) {
    if (bm[x] > 0) {
        res.push_back(x);  
        bm[x]--;  // Decrease freq        
    }
}

return res;

}

int main() { vector a = {1, 2, 1, 3, 1}; vector b = {3, 1, 3, 4, 1}; vector res = findCommon(a, b); for (int x : res) { cout << x << " "; } return 0; }

C

#include <stdio.h> #include <stdlib.h>

#define MAX 1000

// Structure to represent a hashmap in C typedef struct { int key; int count; } HashMap;

void findCommon(int a[], int sizeA, int b[], int sizeB, int res[], int *res_size) { HashMap bm[MAX] = {0}; // hashmap array with default 0 frequency

// Store the frequency of elements in b[]
for (int i = 0; i < sizeB; i++) {
    bm[b[i]].key = b[i];
    bm[b[i]].count++;
}

// Traverse a[] and consider an
// item as common only if its 
// frequency is more than 0 in bm.
for (int i = 0; i < sizeA; i++) {
    if (bm[a[i]].count > 0) {
        res[(*res_size)++] = a[i];
        bm[a[i]].count--;  // Decrease frequency
    }
}

}

int main() { int a[] = {1, 2, 1, 3, 1}; int b[] = {3, 1, 3, 4, 1}; int res[5]; int res_size = 0;

findCommon(a, 5, 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.HashMap; import java.util.List;

class GfG {

static List<Integer> findCommon(int[] a, int[] b) {
    List<Integer> res = new ArrayList<>();
    
    // Store the frequency of elements in b[]
    HashMap<Integer, Integer> bm = new HashMap<>();
    for (int x : b) {
        bm.put(x, bm.getOrDefault(x, 0) + 1);
    }

    // Traverse a[] and consider an
    // item as common only if its 
    // frequency is more than 0 in bm.
    for (int x : a) {
        if (bm.getOrDefault(x, 0) > 0) {
            res.add(x);
            bm.put(x, bm.get(x) - 1);  // Decrease frequency
        }
    }
    return res;
}

public static void main(String[] args) {
    int[] a = {1, 2, 1, 3, 1};
    int[] b = {3, 1, 3, 4, 1};

    List<Integer> res = findCommon(a, b);

    for (int x : res) {
        System.out.print(x + " ");
    }
}

}

Python

def findCommon(a, b):

# Store the frequency of elements in b[]
bm = {}
for x in b:
    bm[x] = bm.get(x, 0) + 1

# Traverse a[] and consider an
# item as common only if its 
# frequency is more than 0 in bm.
res = []
for x in a:
    if bm.get(x, 0) > 0:
        res.append(x)
        bm[x] -= 1  # Decrease frequency
return res

Driver code

a = [1, 2, 1, 3, 1] b = [3, 1, 3, 4, 1]

result = findCommon(a, b)

print(" ".join(map(str, result)))

C#

using System; using System.Collections.Generic;

class GfG { static List findCommon(int[] a, int[] b) { List res = new List();

    // Store the frequency of elements in b[]
    Dictionary<int, int> bm = new Dictionary<int, int>();
    foreach (int x in b) {
        if (bm.ContainsKey(x))
            bm[x]++;
        else
            bm[x] = 1;
    }

    // Traverse a[] and consider an
    // item as common only if its 
    // frequency is more than 0 in bm.
    foreach (int x in a) {
        if (bm.ContainsKey(x) && bm[x] > 0) {
            res.Add(x);
            bm[x]--;  // Decrease frequency
        }
    }
    return res;
}

static void Main() {
    int[] a = {1, 2, 1, 3, 1};
    int[] b = {3, 1, 3, 4, 1};

    List<int> result = findCommon(a, b);

    foreach (int x in result) {
        Console.Write(x + " ");
    }
}

}

JavaScript

function findCommon(a, b) { const res = [];

// Store the frequency of elements in b[]
const bm = {};
for (let x of b) {
    bm[x] = (bm[x] || 0) + 1;
}

// Traverse a[] and consider an
// item as common only if its 
// frequency is more than 0 in bm.
for (let x of a) {
    if (bm[x] > 0) {
        res.push(x);
        bm[x]--;  // Decrease frequency
    }
}

return res;

}

// Driver code const a = [1, 2, 1, 3, 1]; const b = [3, 1, 3, 4, 1];

const result = findCommon(a, b); console.log(result.join(" "));

`

We can do better if two arrays are sorted. Please refer Intersection of Two Sorted Arrays for details.