![]() |
JavaScript can be used to find the common elements in given three sorted arrays. We are given three different sorted arrays, we have to return common elements of three arrays. Example:Input Below are different approaches to finding common elements present in three sorted arrays: Table of Content Brute force ApproachWe will initialize three pointers to traverse each element of the array simultaneously. Now we iterate through the arrays using the pointers within its size limits and compare element present at the current positions of pointers and push common elements into the common array. Now we increase pointers comparing elements present in three arrays and then return the common array. Example: To demonstrate finding common elements present in three sorted arrays using three pointers approach
Output common elements in three array are : [ 4, 5 ] Time complexity: O(n) , n is total numbers of elements across all three arrays Space complexity : O(m) , m is common elements present in arrays Using setWe will create sets from all three input arrays to remove duplicate elements. Now we Iterate through the elements of the first set and check for each element that it exist in both second and third sets. if element exist in both sets then we add it to common array. Return the common array. Example : To demonstrate finding common elements present in three sorted arrays using set
Output common elements in three array using set : [ 4, 5 ] Time complexity : O(n+m) Space complexity: O(n+m) Using HashmapWe will create a hash map to store the count of occurrences of elements from arr1. Now we Iterate through arr2, if an element is found in map, push it into the common array and decrement its count in map. Finally we iterate through arr3 and similarly push elements into finalCommon array if found in map and decrement their count. Return the finalCommon array Example : To demonstrate finding common elements present in three sorted arrays using hashmap.
Output common elements in three array is : [ 4, 5 ] Time complexity : O(n + m + p) Space complexity : O(min(n,m,p)) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 10 |