Array ( [0] => [1] => questions [2] => Strings [3] => Common-elements- )
Given an 3 sorted array of integers. You have to find common element among 3 arrays. If it is not found print -1.
First line contains the size of the first array. Next line contains the m integers separated by the spaces. Next line contains the size of the second array. Next line contains the n integers separated by the spaces . Next line contains the size of the third array. Next line contains the k integers separated by the spaces.
Print the common element.
5 3 6 8 12 15 4 1 4 6 7 3 6 8 10
6
4 2 4 14 25 6 2 4 6 8 9 9 5 3 3 6 7 9
-1
8 4 6 9 12 16 19 21 25 7 9 12 16 19 22 24 25 3 2 6 9
9
Login to see Discussion
Approach1: Brute Force
Step-i) Use three for loops.
Step-ii) Search for the common element using a[i]==a[j] and a[j]==a[k]
Step-iii) Return the index where the elements are equal.
Time Complexity: O(n^3)
Space Complexity: O(n)
Approach2:
Step-i) Use 2 for loops.
Step-ii) Find common element of 2 arrays and place them in new array.
Step-iii) Now use other 2 for loops to find the common of new array and last array.
Step-iv) Finally return the element common.
Time Complexity: O(n^2)
Space Complexity: O(n)
Approach3:
Step-i) Iterate through the array with element as a.
Step-ii) Apply binary search on array 2 and array 3.
Step-iii) If the element a is present in both, then return the value.
Time Complexity: O(n logn)
Space Complexity: O(n)
Approach 4:
Step-i) Iterate through the first array and initialize I and j values with 0.
Step-ii) if a1[i]==a2[j] assign the value to new array, and increase values of I and j.
Step-iii) if a1[i]
Step-v) Repeat the same process to new array and 3rd array.
Step-vi) Then finally return the common element in those 2 arrays.
Time Complexity: O(n)
Space Complexity: O(n)
Note :
Let us know if you can come up with a better approach, mail us at support@theinquisitive.in Your approach will be reviewed and posted with credits to you.
Login to see Solution