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
How to convert NumPy array to dictionary in Python?
The following article explains how to convert numpy array to dictionary in Python. Array in Numpy is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. In Numpy, number of dimensions of the array is called rank of the array. A tuple of integers givi
3 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
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4,
2 min read
Find the Tuples Containing the Given Element from a List of Tuples - Python
The task of finding tuples containing a given element from a list of tuples in Python involves searching for a specific target value within each tuple. For example, given a list like [(1, 2, 3), (4, 5, 6)] and a target 2, the goal is to extract tuples containing 2, resulting in [(1, 2, 3)].Using in
3 min read
Python | Common items among dictionaries
Sometimes, while working with Python, we can come across a problem in which we need to check for the equal items count among two dictionaries. This has an application in cases of web development and other domains as well. Let's discuss certain ways in which this task can be performed. Method #1 : Us
6 min read
Filter Dictionary of Tuples by Condition - Python
This task involves filtering the items of a dictionary based on a specific condition applied to the values, which are tuples in this case. We will check certain conditions for each tuple in the dictionary and select the key-value pairs that satisfy the condition.Given the dictionary a = {'a': (6, 3)
3 min read
Sort Python Dictionary by Key or Value - Python
There are two elements in a Python dictionary-keys and values. You can sort the dictionary by keys, values, or both. In this article, we will discuss the methods of sorting dictionaries by key or value using Python.Sorting Dictionary By Key Using sort()In this example, we will sort the dictionary by
6 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