
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Common Elements in Three Sorted Arrays in Python
The given task is to find the common element in three sorted arrays.
Input Output Scenario
Following is an input-output scenario -
Input Arrays: array1 = [1001, 1004, 1007, 1009, 1015, 1020] array2 = [1002, 1004, 1009, 1013, 1015, 1022] array3 = [1000, 1004, 1009, 1015, 1021] Output: [1004, 1009, 1015]
This is useful in multiple scenarios, for example, if we are filtering mutual friends of three different users in apps like Facebook or comparing product availability in three different e-commerce applications on a third-party website. We are filtering elements that are common in multiple datasets.
Finding Common Elements in three Sorted Arrays
Since we need to find the common elements in 3 different arrays, we need to use a three-pointer technique, i.e, we use 3 pointers to traverse elements. This technique is typically used to access or traverse through the elements of data structures like arrays, linked lists.
Since the arrays are already sorted, traversing through them is easier. Following is the algorithm -
- Initialize three pointers (indexes) for the arrays A1, A2, and A3.
- Loop through three Arrays while the arrays are nonempty.
- At each iteration, verify each value of A1, A2, andA3. If the values are the same, If all three elements are equal, then add it to the result list and increment all three pointers.
- If the elements are not equal, increment the pointer pointing to the smallest element among the three.
- Continue until one pointer reaches the end of the array.
Example
Let's look at the following example, where we are going to initialize the pointers 'i, j,k=0' for traversing the three arrays.
def demo(x, y, z): i = j = k = 0 a = [] while i < len(x) and j < len(y) and k < len(z): if x[i] == y[j] == z[k]: if not a or a[-1] != x[i]: a.append(x[i]) i += 1 j += 1 k += 1 elif x[i] < y[j]: i += 1 elif y[j] < z[k]: j += 1 else: k += 1 return a x = [1,2,3,4,10] y = [2,4,6,8,10] z = [4,10,23,25,26] result = demo(x, y, z) print("Result :", result)
The output of the above program is as follows -
Result : [4, 10]