File tree Expand file tree Collapse file tree
Sprint-1/JavaScript/findCommonItems Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11/**
22 * Finds common items between two arrays.
33 *
4- * Time Complexity:
5- * Space Complexity:
6- * Optimal Time Complexity:
7- *
4+ * Time Complexity: O(n * m)
5+ * Space Complexity: O(k)---> where k is the number of common items
6+ * Optimal Time Complexity: O(n + m)
7+ * Explanation: The function uses the filter method to iterate through each item in the first array and
8+ * checks if it exists in the second array using the includes method.
9+ * This results in a time complexity of O(n * m) because for each item in the first array,
10+ * we are checking against all items in the second array.
11+ * The space complexity is O(k) because we are creating a new array to store the common items,
12+ * where k is the number of common items found.
813 * @param {Array } firstArray - First array to compare
914 * @param {Array } secondArray - Second array to compare
1015 * @returns {Array } Array containing unique common items
1116 */
12- export const findCommonItems = ( firstArray , secondArray ) => [
13- ...new Set ( firstArray . filter ( ( item ) => secondArray . includes ( item ) ) ) ,
14- ] ;
17+ export const findCommonItems = ( firstArray , secondArray ) => {
18+ const lookup = new Set ( secondArray ) ;
19+ const result = new Set ( ) ;
20+ for ( const item of firstArray ) {
21+ if ( lookup . has ( item ) ) {
22+ result . add ( item ) ;
23+ }
24+ }
25+ return [ ...result ] ;
26+ } ;
You can’t perform that action at this time.
0 commit comments