Find Common Elements in Two Arrays in Python
Last Updated :
23 Jul, 2025
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 5
Explanation: 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 4
Explanation: 0, 2 and 4 are common to both the arrays.
Find Common Elements in Two Arrays using Brute Force:
This is a brute force approach, simply traverse in the first array, for every element of the first array traverse in the second array to find whether it exists there or not, if true then check it in the result array (to avoid repetition), after that if we found that this element is not present in result array then print it and store it in the result array.
Step-by-step approach:
- Iterate over each element in
arr1
. - For each element in
arr1
, iterate over each element in arr2
. - Compare the current element of
arr1
with each element of arr2
. - If a common element is found between the two arrays, proceed to the next steps. Otherwise, continue to the next iteration.
- Check if the common element found is already present in the result array.
- If the common element is not a duplicate, add it to the result array.
- Print the common elements found during the iterations.
Below is the implementation of the above approach:
Python
# Python Program for find commom element using two array
import array
arr1 = array.array('i', [1, 2, 3, 4, 5])
arr2 = array.array('i', [3, 4, 5, 6, 7])
result = array.array('i')
print("Common elements are:", end=" ")
# To traverse array1.
for i in range(len(arr1)):
# To traverse array2.
for j in range(len(arr2)):
# To match elements of array1 with elements of array2.
if arr1[i] == arr2[j]:
# Check whether the found element is already present in the result array or not.
if arr1[i] not in result:
result.append(arr1[i])
print(arr1[i], end=" ")
break
OutputCommon elements are: 3 4 5
Time Complexity: O(n * m), where n is the number of elements in array arr1[] and m is the number of elements in arr2[].
Auxiliary Space: O(k), where k is the number of common elements between the two arrays.
Find Common Elements in Two Arrays Using List Comprehension:
To find the common elements in two arrays in python, we have used list comprehension. For each element X in arr1, we check if X is present in arr2 and store it in a list.
Step-by-step approach:
- Use list comprehension to iterate over each element
x
in arr1
.- For each element, check if it exists in
arr2
. If it does, add it to a new array called common_elements
.
- Convert the
common_elements
array to a list and return it. - Print the result.
Below is the implementation of the above approach:
Python
# Python Program for the above approach
from array import array
def find_common_elements(arr1, arr2):
common_elements = array('i', [x for x in arr1 if x in arr2])
return list(common_elements)
# Driver Code
arr1 = array('i', [1, 2, 3, 4, 5])
arr2 = array('i', [3, 4, 5, 6, 7])
common_elements = find_common_elements(arr1, arr2)
print("Common elements:", common_elements)
OutputCommon elements: [3, 4, 5]
Time Complexity : O(n*m)
Auxiliary Space: O(k), where k is the number of common elements between the two arrays.
Find Common Elements in Two Arrays using Sorting:
To find the common elements in two arrays in Python, we have to first sort the arrays, then just iterate in the sorted arrays to find the common elements between those arrays.
Step-by-step approach:
- Sort both arrays arr1 and arr2 in non-decreasing order.
- Initialize two pointers pointer1 and pointer2 to the beginning of both arrays.
- Iterate through both arrays simultaneously:
- If the elements pointed by pointer1 and pointer2 are equal, add the element to the result vector and move both pointers forward.
- If the element in arr1 pointed by pointer1 is less than the element in arr2 pointed by pointer2, move pointer1 forward.
- If the element in arr2 pointed by pointer2 is less than the element in arr1 pointed by pointer1, move pointer2 forward.
- Repeat this process until one of the pointers reaches the end of its array.
- Return the result containing the common elements found in both arrays.
Below is the implementation of the above approach:
Python
import array
def find_common_elements(arr1, arr2):
# Convert arrays to lists for sorting
arr1_list = list(arr1)
arr2_list = list(arr2)
# Sort both lists in non-decreasing order
arr1_list.sort()
arr2_list.sort()
# Initialize pointers
pointer1 = 0
pointer2 = 0
# Initialize an empty array to store common elements
common_elements = array.array('i')
# Iterate through both arrays simultaneously
while pointer1 < len(arr1_list) and pointer2 < len(arr2_list):
# If the elements pointed by pointer1 and pointer2 are equal
if arr1_list[pointer1] == arr2_list[pointer2]:
# Add the element to the result array
common_elements.append(arr1_list[pointer1])
# Move both pointers forward
pointer1 += 1
pointer2 += 1
# If the element in arr1 pointed by pointer1 is less than the element in arr2 pointed by pointer2
elif arr1_list[pointer1] < arr2_list[pointer2]:
# Move pointer1 forward
pointer1 += 1
# If the element in arr2 pointed by pointer2 is less than the element in arr1 pointed by pointer1
else:
# Move pointer2 forward
pointer2 += 1
return common_elements
# Test the function with example arrays
arr1 = array.array('i', [1, 2, 3, 4, 5])
arr2 = array.array('i', [3, 4, 5, 6, 7])
common_elements = find_common_elements(arr1, arr2)
print "Common elements:",
for element in common_elements:
print element,
OutputCommon elements: 3 4 5
Time Complexity: O(N log(N)+ M log(M)), where N is the size of the first array and M is the size of the second array.
Auxilliary Space: O(N+M)
Find Common Elements in Two Arrays Using Sets:
To find the common elements in two arrays in Python, in this approach we will use sets. Initially, we convert both the arrays arr1 and arr2 to sets set1 and set2. Then, we use the intersection method of set to find the common elements in both the sets. Finally, we return the common elements as a list.
Step-by-step approach:
- Import the
array
module to use arrays in Python. - Define a function named
find_common_elements
that takes two arrays (arr1
and arr2
) as input. - Within the function, convert both arrays to sets (
set1
and set2
) for faster lookup. - Find the intersection of the sets (
set1.intersection(set2)
), which represents the common elements between the two arrays. - Convert the set of common elements to a list and return it.
- Initialize two arrays
arr1
and arr2
. Call the find_common_elements
function with these arrays and store the result in common_elements
. - Print the result.
Below is the implementation of the above approach:
Python
# Python Program for the above approach
from array import array
def find_common_elements(arr1, arr2):
# Convert arrays to sets for faster lookup
set1 = set(arr1)
set2 = set(arr2)
# Find intersection of the sets (common elements)
common_elements = set1.intersection(set2)
return list(common_elements)
# Driver Code
arr1 = array('i', [1, 2, 3, 4, 5])
arr2 = array('i', [3, 4, 5, 6, 7])
common_elements = find_common_elements(arr1, arr2)
print("Common elements:", common_elements)
OutputCommon elements: [3, 4, 5]
Time Complexity : O(n+m)
Auxiliary Space: O((n+m+k), where k is the number of common elements between the two arrays.
Find Common Elements in Two Arrays Using Hash Maps
In this approach, we can utilize hash maps to efficiently find the common elements between the two arrays. We'll create a hash map to the store the frequency of the each element in the first array and then iterate through the second array to the check if each element exists in the hash map. If an element exists in the hash map and its frequency is greater than 0 and we'll add it to the list of common elements and decrease its frequency in the hash map.
Here's the step-by-step algorithm:
- Create a hash map to store the frequency of the each element in the first array where the key is the element and the value is its frequency.
- Iterate through the second array.
- For each element in the second array and check if it exists in the hash map and its frequency is greater than 0.
- If both conditions are met add the element to the list of the common elements and decrease its frequency in the hash map.
- After iterating through the second array, return the list of the common elements.
Example code:
Python
def GFG(arr1, arr2):
# Create a hash map to store the frequency of the each element in arr1
frequency_map = {}
for num in arr1:
frequency_map[num] = frequency_map.get(num, 0) + 1
# Initialize a list to store the common elements
common_elements = []
# Iterate through arr2 to the find common elements
for num in arr2:
if num in frequency_map and frequency_map[num] > 0:
common_elements.append(num)
frequency_map[num] -= 1
return common_elements
# Test the function with the example arrays
arr1 = [1, 2, 3, 4, 5]
arr2 = [3, 4, 5, 6, 7]
common_elements = GFG(arr1, arr2)
print("Common elements:", common_elements)
output :
Common elements: 3, 4, 5
Time Complexity : O(n+m)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem