Python | Find common elements in three sorted arrays by dictionary intersection
Given three arrays sorted in non-decreasing order, print all common elements in these arrays.
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 existing solution for this problem please refer Find common elements in three sorted arrays link. We can solve this problem quickly in python using intersection of dictionaries. 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.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course