Open In App

Find common elements in three sorted arrays by dictionary intersection

Last Updated : 05 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

Python | Dictionary initialization with common dictionary
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with records values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain way in which this task can be performed. Method 1: Using zip
7 min read
Python program to find common elements in three lists using sets
Prerequisite: Sets in Python Given three arrays, we have to find common elements in three sorted lists using sets. 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] Method 1: We have given
5 min read
Python counter and dictionary intersection example (Make a string using deletion and rearrangement)
Given two strings, find if we can make first string from second by deleting some characters from second and rearranging remaining characters. Examples: Input : s1 = ABHISHEKsinGH : s2 = gfhfBHkooIHnfndSHEKsiAnG Output : Possible Input : s1 = Hello : s2 = dnaKfhelddf Output : Not Possible Input : s1 = GeeksforGeeks : s2 = rteksfoGrdsskGeggehes Outpu
2 min read
Python Program For Finding Intersection Of Two Sorted Linked Lists
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.  Example:  Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Output: 2->4->6. The elements 2, 4, 6 are common in
4 min read
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 intersection_update() works ? Suppose we have two sets A
1 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Python - Common list elements and dictionary values
Given list and dictionary, extract common elements of List and Dictionary Values. Input : test_list = ["Gfg", "is", "Best", "For"], subs_dict = {4 : "Gfg", 8 : "Geeks", 9 : " Good", } Output : ['Gfg'] Explanation : "Gfg" is common in both list and dictionary value. Input : test_list = ["Gfg", "is", "Best", "For", "Geeks"], subs_dict = {4 : "Gfg", 8
3 min read
Python program to check if the list contains three consecutive common numbers in Python
Our task is to print the element which occurs 3 consecutive times in a Python list. Example : Input : [4, 5, 5, 5, 3, 8] Output : 5 Input : [1, 1, 1, 64, 23, 64, 22, 22, 22] Output : 1, 22 Approach : Create a list.Create a loop for range size – 2.Check if the element is equal to the next element.Again check if the next element is equal to the next
3 min read
heapq in Python to print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order. Examples: Input : mat= [[10, 20, 30, 40], [15, 25, 35, 45], [27, 29, 37, 48], [32, 33, 39, 50]] Output : Elements of matrix in sorted order [10, 15, 20, 25, 27, 29, 30, 32, 33, 35, 37, 39, 40, 45, 48, 50] This problem h
2 min read
Three Level Nested Dictionary Python
In Python, a dictionary is a built-in data type used to store data in key-value pairs. Defined with curly braces `{}`, each pair is separated by a colon `:`. This allows for efficient representation and easy access to data, making it a versatile tool for organizing information. What is 3 Level Nested Dictionary?A 3-level nested dictionary refers to
4 min read
three90RightbarBannerImg