Find common elements in three sorted arrays by dictionary intersection
Last Updated :
05 Sep, 2023
One way to efficiently find shared items in three sorted arrays is by using dictionary intersection. However, it's important to note that dictionaries are commonly used for unique keys, so if there are duplicate elements in your arrays, some adjustments may be needed to make this approach work. Given three arrays sorted in non-decreasing order, print all common elements in these arrays in Python.
Examples:
Input: ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
Output: [80, 20]
Input: ar1 = [1, 5, 5]
ar2 = [3, 4, 5, 5, 10]
ar3 = [5, 5, 10, 20]
Output: [5, 5]
We have an existing solution for this problem Please refer to Find common elements in three sorted Arrays. We can solve this problem quickly in Python using the intersection of dictionaries.
Find common elements In 3 sorted Arrays using Collection.counter() Function
The approach is simple, First convert all three lists into dictionaries having elements as keys and their frequencies as value, using Counter() method. Now perform intersection operation for three dictionaries, this will result us dictionary having common elements among three array list with their frequencies.
Python3
# Function to find common elements in three
# sorted arrays
from collections import Counter
def commonElement(ar1,ar2,ar3):
# first convert lists into dictionary
ar1 = Counter(ar1)
ar2 = Counter(ar2)
ar3 = Counter(ar3)
# perform intersection operation
resultDict = dict(ar1.items() & ar2.items() & ar3.items())
common = []
# iterate through resultant dictionary
# and collect common elements
for (key,val) in resultDict.items():
for i in range(0,val):
common.append(key)
print(common)
# Driver program
if __name__ == "__main__":
ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
commonElement(ar1,ar2,ar3)
Output:
[80, 20]
Find common elements In 3 sorted Arrays using Three Pointers
This approach uses a three-pointer approach to find common elements in the three sorted arrays. The code defines a function called common_elements. This function efficiently finds and returns the common elements among three sorted arrays by using three pointers to iterate through the arrays and comparing their elements. The function increments the pointers based on the result of the comparisons and collects common elements in a list called common. Finally, the function returns the common list.
Python3
def common_elements(ar1, ar2, ar3):
n1, n2, n3 = len(ar1), len(ar2), len(ar3)
i, j, k = 0, 0, 0
common = []
while i < n1 and j < n2 and k < n3:
if ar1[i] == ar2[j] == ar3[k]:
common.append(ar1[i])
i += 1
j += 1
k += 1
elif ar1[i] < ar2[j]:
i += 1
elif ar2[j] < ar3[k]:
j += 1
else:
k += 1
return common
ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
print(common_elements(ar1, ar2, ar3)) # Output: [20, 80]
ar1 = [1, 5, 5]
ar2 = [3, 4, 5, 5, 10]
ar3 = [5, 5, 10, 20]
print(common_elements(ar1, ar2, ar3)) # Output: [5, 5]
Output:
[20, 80]
[5, 5]
Time complexity: Â O(n), where n is the length of the largest input array.
Space complexity: O(1), as it only uses a fixed-size list for storing common elements.
Find common elements In 3 sorted arrays using collections.OrderedDict
In this code, we are finding the common elements among three sorted arrays namely ar1, ar2, and ar3 by using ordered dictionaries. Firstly, we initialize empty lists and create ordered dictionaries for each of the arrays in order to preserve the order of elements. Next, we iterate through the dictionaries, comparing keys (values) to identify common elements. Whenever we find a common element, we append it to a list called 'lst'. Finally, we print the list of common elements. In this case, the common elements found are 20 and 80.
Python
from collections import OrderedDict
ar1 = [1, 5, 10, 20, 40, 80]
ar2 = [6, 7, 20, 80, 100]
ar3 = [3, 4, 15, 20, 30, 70, 80, 120]
lst = []
dict1 = OrderedDict.fromkeys(ar1)
dict2 = OrderedDict.fromkeys(ar2)
dict3 = OrderedDict.fromkeys(ar3)
for values1, keys1 in dict1.items():
for values2, keys2 in dict2.items():
for values3, keys3 in dict3.items():
if values1 == values2 == values3:
lst.append(values1)
print("List with common elements: ",lst)
Output:
('List with common elements: ', [20, 80])
Time Complexity: O(n*n*n)
Space Complexity: O(min(n1, n2, n3))
Similar Reads
intersection_update() in Python to find common elements in n arrays We are given list of n number of arrays, find all common elements in given arrays ? Examples: Input : arr = [[1,2,3,4], [8,7,3,2], [9,2,6,3], [5,1,2,3]] Output : Common Elements = [2,3] We can solve this problem quickly in python using intersection_update() method of Set() data structure. How inters
1 min read
Python - Find the Common Keys from two Dictionaries In this article, we will learn how can we print common keys from two Python dictionaries. We will see that there are multiple methods one can do this task. From brute force solutions of nested loops to optimize ones that trade between space and time to decrease the time complexity we will see differ
4 min read
Intersection of two Arrays in Python ( Lambda expression and filter function ) Finding the intersection of two arrays using a lambda expression and the filter() function means filtering elements from one array that exist in the other. The lambda defines the condition (x in array2), and filter() applies it to the first array to extract common elements.For example, consider two
1 min read
How to Compare List of Dictionaries in Python Comparing a list of dictionaries in Python involves checking if the dictionaries in the list are equal, either entirely or based on specific key-value pairs. This process helps to identify if two lists of dictionaries are identical or have any differences. The simplest approach to compare two lists
3 min read
Find common values between two NumPy arrays In this article, we are going to discuss how to find out the common values between 2 arrays. To find the common values, we can use the numpy.intersect1d(), which will do the intersection operation and return the common values between the 2 arrays in sorted order. Syntax: numpy.intersect1d(arr1, arr2
2 min read