VOOZH about

URL: https://www.geeksforgeeks.org/dsa/common-elements-in-two-arrays/

⇱ Common Elements in Two Arrays - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Common Elements in Two Arrays

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 : {}

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[]

Output
1 1 3 

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[]

Output
1 1 3 

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


Comment