![]() |
VOOZH | about |
Given three sorted arrays in non-decreasing order, find all common elements in non-decreasing order across these arrays. If there are no such elements return an empty array.
Note: In case of duplicate common elements, include each element only once in the result.
Examples:
Input: a[] = [1, 5, 10, 20, 30], b[] = [5, 13, 15, 20], c[] = [5, 20]
Output: 5 20
Explanation: 5 and 20 are common in all the arrays.Input: a[] = [1, 2, 3, 4, 5], b[] = [6, 7], c[] = [8, 9, 10]
Output: []
Explanation: There are no common elements in a, b and c.Input: a[] = [2, 5, 10, 30], b[] = [5, 20, 34], c[] = [5, 13, 19]
Output: 5
Explanation: 5 is common in all the arrays.
Table of Content
The idea is to use a Hash Map to track elements common across all three arrays while avoiding duplicates. Each element is marked step-by-step to identify those present in all arrays, and the final result is sorted to maintain non-decreasing order.
Dry run for a[] = [1, 5, 10, 20, 30], b[] = [5, 13, 15, 20], c[] = [5, 20]:
Final output, 5 20
Important Points:
5 20
Time Complexity: O((n1 + n2 + n3) + K log K), because we traverse all arrays once and sort K common elements.
Auxiliary Space: O(n1), because the hash map stores elements from the first array.
We can efficiently find common elements in three sorted arrays using the three-pointer technique, eliminating the need for merging or intersecting the arrays.
Since the arrays are sorted in non-decreasing order, the smallest element among the three pointers at any moment will always be the smallest in the merged arrays. Leveraging this property, we can optimize our approach as follows:
Working of Three pointers approach:
5 20