Find common elements In 3 sorted arrays in Python
One Subscription, For Everything
The new cool way of learning and upskilling -
One Subscription access everything
Get Access to PrepInsta Prime
from FAANG/IITs/TOP MNC's

PrepInstaPrime
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others.
Login/Signup to comment












# Common Element in all three arrays
arr1 = list(map(int, input(“Enter the values for Array_1 : “).split()))
arr2 = list(map(int, input(“Enter the values for Array_2 : “).split()))
arr3 = list(map(int, input(“Enter the values for Array_3 : “).split()))
arr1.sort()
arr2.sort()
arr3.sort()
common = []
for i in range(len(arr1)+1):
if i in arr2:
if i in arr3:
common.append(i)
else:
continue
else:
continue
print(“Common Elements in all three Array :”, common)
def common_elements(arr1, arr2, arr3):
i = j = k = 0
result = []
while i < len(arr1) and j < len(arr2) and k < len(arr3):
# If all three elements are equal, it's common
if arr1[i] == arr2[j] == arr3[k]:
result.append(arr1[i])
i += 1
j += 1
k += 1
# If arr1[i] is smaller, move i forward
elif arr1[i] < arr2[j]:
i += 1
# If arr2[j] is smaller, move j forward
elif arr2[j] < arr3[k]:
j += 1
# Otherwise, move k forward
else:
k += 1
return result
# Example usage:
arr1 = [1, 5, 10, 20, 40, 80]
arr2 = [6, 7, 20, 80, 100]
arr3 = [3, 4, 15, 20, 30, 70, 80, 120]
print(common_elements(arr1, arr2, arr3))
def find_common_elements(arr1, arr2, arr3):
i = j = k = 0
common = []
while i < len(arr1) and j < len(arr2) and k < len(arr3):
# If all three are equal
if arr1[i] == arr2[j] == arr3[k]:
if not common or common[-1] != arr1[i]: # Avoid duplicates
common.append(arr1[i])
i += 1
j += 1
k += 1
# Find the smallest and move its pointer forward
elif arr1[i] < arr2[j]:
i += 1
elif arr2[j] < arr3[k]:
j += 1
else:
k += 1
return common