Common Elements in Two Arrays
Last Updated :
17 Oct, 2024
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 : {}
Naive Approach - O(n*m) Time and O(1) Space
- Initialize an empty array res[] to store result
- 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].
- Return res[]
C++
#include <iostream>
#include <vector>
using namespace std;
vector<int> findCommon(vector<int>& a, vector<int>& b) {
vector<int> res;
vector<bool> 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<int> a = {1, 2, 1, 3, 1};
vector<int> 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<int> findCommon(int[] a, int[] b) {
List<int> res = new List<int>();
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
- Create a hash map bm and store every item of b[] as key and its frequency as value.
- Create an empty array res[] to store result
- 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.
- Return res[]
C++
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
vector<int> findCommon(vector<int>& a, vector<int>& 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<int> a = {1, 2, 1, 3, 1};
vector<int> b = {3, 1, 3, 4, 1};
vector<int> 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<int> findCommon(int[] a, int[] b) {
List<int> res = new List<int>();
// 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.
Similar Reads
Find Common Elements in Two Arrays in Python Given two arrays arr1[] and arr2[], the task is to find all the common elements among them. Examples: Input: arr1[] = {1, 2, 3, 4, 5}, arr2[] = {3, 4, 5, 6, 7}Output: 3 4 5Explanation: 3, 4 and 5 are common to both the arrays. Input: arr1: {2, 4, 0, 5, 8}, arr2: {0, 1, 2, 3, 4}Output: 0 2 4Explanati
8 min read
Find common elements in three sorted arrays Given three sorted arrays in non-decreasing order, print all common elements in non-decreasing order across these arrays. If there are no such elements return an empty array. In this case, the output will be -1.Note: In case of duplicate common elements, print only once.Examples: Input: arr1[] = [1,
12 min read
Count number of common elements between two arrays Given two arrays a[] and b[], the task is to find the count of common elements in both the given arrays. Note that both the arrays contain distinct (individually) positive integers.Examples: Input: a[] = {1, 2, 3}, b[] = {2, 4, 3} Output: 2 2 and 3 are common to both the arrays.Input: a[] = {1, 4, 7
15 min read
Intersection of two Arrays Given two arrays a[] and b[], find their intersection â the unique elements that appear in both. Ignore duplicates, and the result can be in any order.Input: a[] = [1, 2, 1, 3, 1], b[] = [3, 1, 3, 4, 1]Output: [1, 3]Explanation: 1 and 3 are the only common elements and we need to print only one occu
12 min read
Intersection of Two Arrays with Distinct Elements 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 tw
9 min read