Find common elements In 3 sorted arrays in Python

python program to find common elements between three sorted array

Common elements in three sorted arrays

In this article we will see a python program to find Common elements in three sorted arrays. User will give us three sorted array. And we are required to find common elements between these arrays.

Let us consider an example for better understanding.

  • Array1= [1, 2, 3]
  • Array2= [2, 3, 4]
  • Array3= [3, 4, 5]
  • Common elements between array1,array2 & array3 is : 3

Method 1

Algorithm

  • Step 1: Initialize array1 and assign values
  • Step 2: Initialize array2 and assign values
  • Step 3: Initialize array3 and assign values
  • Step 4: Print all  the arrays
  • Step 5: Call the function find
Algorithm for function find
  • Step 1: Declare all the three arrays as set
  • Step 2: Apply set intersection operation on all three arrays to get desired output.
common elements between three sorted array in python

Python Code

Run
def find(arr1, arr2, arr3):
    print("Common elements between all three array: ", end="")
    arr1 = set(arr1)
    arr2 = set(arr2)
    arr3 = set(arr3)
    print(arr1 & arr2 & arr3)


array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]
array3 = [3, 5, 6, 7]

print("Array1 = ", array1)
print("Array2 = ", array2)
print("Array3 = ", array3)

find(array1, array2, array3)

Output

Array1 = [1, 2, 3, 4]
Array2 = [3, 4, 5, 6]
Array3 = [3, 5, 6, 7]
Common elements between all three array: {3}

Method 2

Algorithm

  • Step 1: Initialize array1 and assign values
  • Step 2: Initialize array2 and assign values
  • Step 3: Initialize array3 and assign values
  • Step 4: Print all  the arrays
  • Step 5: Call the function find
Algorithm for function find
  • Step 1: Iterate on the elements of array1 using variable i and check if it is present in array2 and array3. If present in both print the element.

Python Code

Run
def find(arr1, arr2, arr3):
    print("Common elements between all three array: ", end="")
    for i in arr1:
        if i in arr2 and i in arr3:
            print(i, end=" ")


array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]
array3 = [3, 5, 6, 7]

print("Array1 = ", array1)
print("Array2 = ", array2)
print("Array3 = ", array3)

find(array1, array2, array3)

Output

Array1 = [1, 2, 3, 4]
Array2 = [3, 4, 5, 6]
Array3 = [3, 5, 6, 7]
Common elements between all three array: {3}

Comments