SolvingCodingProblem

Run Settings
LanguageJavaScript
Language Version
Run Command
// Given 2 arrays, create a function that let's a user know (true/false) whether these two arrays contain any common items //For Example: // const array1 = ['a', 'b', 'c', 'x']; // const array2 = ['z', 'y', 'a', 'i']; // //should return false. // //----------- // //const array1 = ['a', 'b', 'c', 'x'];//const array2 = ['z', 'y', 'x']; // //should return true. // // 2 parameters - arrays - no size limit // // return true or false // // O(a + b) // const containsCommonItems = (arr1, arr2) => { // // Loop through first array and make an object // // where the elements are properties // let map = {}; // for (let i = 0; i < arr1.length; i++) { // if(!map[arr1[i]]) { // const item = arr1[i]; // map[item] = true; // } // } // // console.log(map); // // Loop through second array and see if // // elements exist object properties // for (let j = 0; j < arr2.length; j++) { // if(map[arr2[j]]) { // return true; // } // } // return false; // } // const containsCommonItems2 = (arr1, arr2) => { // return arr1.some(element => arr2.includes(element)) // } // console.log(containsCommonItems(array1, array2)); // console.log(containsCommonItems2(array1, array2)); // Google Interview Example // Naive function hasPairWithSum(arr, sum){ var len = arr.length; for(var i = 0; i<len-1; i++) { for (var j = i+1; j<len; j++) { if (arr[i] + arr[j] === sum) return true; } } return false; } // Better function hasPairWithSum2(arr, sum) { const mySet = new Set(); const len = arr.length; for (let i = 0; i < len; i++) { if (mySet.has(arr[i])) { return true; } mySet.add(sum - arr[i]); } return false; } console.log(hasPairWithSum2([6,4,3,2,1,7], 9))
Editor Settings
Theme
Key bindings
Full width
Lines