Find common elements in three sorted arrays in Python
In this tutorial, we’re going to learn how to find the common elements in three sorted arrays in Python. Firstly, we need to know what an array is. An array is a set of orderly arranged data of the same type, that are stored in contiguous memory locations. In Python, we can create an array by importing the ‘array’ module. The syntax for declaring an array:
array('data-type',[value list]), specifying the data type of the array along with the list of elements that will be stored in the array.
Let’s first check how to import the array module in Python:
import array as arr
Program to find common element(s) in 3 sorted arrays
Now, we’ll learn how to find the common element(s) from those 3 sorted arrays, in Python:
(Note that: we have added ‘
array() first parameter. Here
i is nothing but a type code in Python. It actually denotes that the values are of integers type.)
import array as arr a1=arr.array('i',[1,2,3,4]); a2=arr.array('i',[3,4,6,8]); a3=arr.array('i',[3,4,9,11]); l= f=0 def find_common(a1,a2,a3): for i in range(len(a1)): for j in range(len(a2)): for k in range(len(a3)): if(a2[j]==a3[k]): temp=a2[j]; if(a1[i]==temp): l.append(a1[i]); f=1 break; else: continue; if(f>0): print("Common element(s) found in the arrays:\n",l); else: print("No common element(s) found"); find_common(a1,a2,a3);
Common element(s) found in the arrays: [3, 4]
After executing the above code, we’ll find a list containing the common elements of the 3 arrays get printed. In this program, we’ve already initialized the arrays with a set of values. The user can use a custom set of values for the same. Now, we’re able to find out the common elements from different arrays using this simple technique.