1.1 Given an array of integers, find the largest product yielded from three of the integers
varunsortedArray=[-10,7,29,30,5,-10,-70];computeProduct(unsortedArray);// 21000functionsortIntegers(a,b){returna-b;}// Greatest product is either (min1 * min2 * max1 || max1 * max2 * max3)functioncomputeProduct(unsorted){varsortedArray=unsorted.sort(sortIntegers),product1=1,product2=1,array_n_element=sortedArray.length-1;// Get the product of three largest integers in sorted arrayfor(varx=array_n_element;x>array_n_element-3;x--){product1=product1*sortedArray[x];}product2=sortedArray[0]*sortedArray[1]*sortedArray[array_n_element];if(product1>product2)returnproduct1;returnproduct2;}
1.2 Being told that an unsorted array contains (n - 1) of n consecutive numbers (where the bounds are defined), find the missing number in O(n) time
// The output of the function should be 8vararrayOfIntegers=[2,5,1,4,9,6,3,7];varupperBound=9;varlowerBound=1;findMissingNumber(arrayOfIntegers,upperBound,lowerBound);// 8functionfindMissingNumber(arrayOfIntegers,upperBound,lowerBound){// Iterate through array to find the sum of the numbersvarsumOfIntegers=0;for(vari=0;i<arrayOfIntegers.length;i++){sumOfIntegers+=arrayOfIntegers[i];}// Find theoretical sum of the consecutive numbers using a variation of Gauss Sum.// Formula: [(N * (N + 1)) / 2] - [(M * (M - 1)) / 2];// N is the upper bound and M is the lower boundupperLimitSum=(upperBound*(upperBound+1))/2;lowerLimitSum=(lowerBound*(lowerBound-1))/2;theoreticalSum=upperLimitSum-lowerLimitSum;returntheoreticalSum-sumOfIntegers;}
1.4 Given an array of integers, find the largest difference between two elements such that the element of lesser value must come before the greater element
vararray=[7,8,4,9,9,15,3,1,10];// [7, 8, 4, 9, 9, 15, 3, 1, 10] would return `11` based on the difference between `4` and `15`// Notice: It is not `14` from the difference between `15` and `1` because 15 comes before 1.findLargestDifference(array);functionfindLargestDifference(array){// If there is only one element, there is no differenceif(array.length<=1)return-1;// currentMin will keep track of the current lowestvarcurrentMin=array[0];varcurrentMaxDifference=0;// We will iterate through the array and keep track of the current max difference// If we find a greater max difference, we will set the current max difference to that variable// Keep track of the current min as we iterate through the array, since we know the greatest// difference is yield from `largest value in future` - `smallest value before it`for(vari=1;i<array.length;i++){if(array[i]>currentMin&&(array[i]-currentMin>currentMaxDifference)){currentMaxDifference=array[i]-currentMin;}elseif(array[i]<=currentMin){currentMin=array[i];}}// If negative or 0, there is no largest differenceif(currentMaxDifference<=0)return-1;returncurrentMaxDifference;}
1.5 Given an array of integers, return an output array such that output[i] is equal to the product of all the elements in the array other than itself. (Solve this in O(n) without division)
varfirstArray=[2,2,4,1];varsecondArray=[0,0,0,2];varthirdArray=[-2,-2,-3,2];productExceptSelf(firstArray);// [8, 8, 4, 16]productExceptSelf(secondArray);// [0, 0, 0, 0]productExceptSelf(thirdArray);// [12, 12, 8, -12]functionproductExceptSelf(numArray){varproduct=1;varsize=numArray.length;varoutput=[];// From first array: [1, 2, 4, 16]// The last number in this case is already in the right spot (allows for us)// to just multiply by 1 in the next step.// This step essentially gets the product to the left of the index at index + 1for(varx=0;x<size;x++){output.push(product);product=product*numArray[x];}// From the back, we multiply the current output element (which represents the product// on the left of the index, and multiplies it by the product on the right of the element)varproduct=1;for(vari=size-1;i>-1;i--){output[i]=output[i]*product;product=product*numArray[i];}returnoutput;}
1.6 Find the intersection of two arrays. An intersection would be the common elements that exists within both arrays. In this case, these elements should be unique!
varfirstArray=[2,2,4,1];varsecondArray=[1,2,0,2];intersection(firstArray,secondArray);// [2, 1]functionintersection(firstArray,secondArray){// The logic here is to create a hashmap with the elements of the firstArray as the keys.// After that, you can use the hashmap's O(1) look up time to check if the element exists in the hash// If it does exist, add that element to the new array.varhashmap={};varintersectionArray=[];firstArray.forEach(function(element){hashmap[element]=1;});// Since we only want to push unique elements in our case... we can implement a counter to keep track of what we already addedsecondArray.forEach(function(element){if(hashmap[element]===1){intersectionArray.push(element);hashmap[element]++;}});returnintersectionArray;// Time complexity O(n), Space complexity O(n)}
2.1 Given a string, reverse each word in the sentence"Welcome to this Javascript Guide!" should be become "emocleW ot siht tpircsavaJ !ediuG"
varstring="Welcome to this Javascript Guide!";// Output becomes !ediuG tpircsavaJ siht ot emocleWvarreverseEntireSentence=reverseBySeparator(string,"");// Output becomes emocleW ot siht tpircsavaJ !ediuGvarreverseEachWord=reverseBySeparator(reverseEntireSentence," ");functionreverseBySeparator(string,separator){returnstring.split(separator).reverse().join(separator);}
2.2 Given two strings, return true if they are anagrams of one another"Mary" is an anagram of "Army"
varfirstWord="Mary";varsecondWord="Army";isAnagram(firstWord,secondWord);// truefunctionisAnagram(first,second){// For case insensitivity, change both words to lowercase.vara=first.toLowerCase();varb=second.toLowerCase();// Sort the strings, and join the resulting array to a string. Compare the resultsa=a.split("").sort().join("");b=b.split("").sort().join("");returna===b;}
2.3 Check if a given string is a palindrome"racecar" is a palindrome. "race car" should also be considered a palindrome. Case sensitivity should be taken into account
isPalindrome("racecar");// trueisPalindrome("race Car");// truefunctionisPalindrome(word){// Replace all non-letter chars with "" and change to lowercasevarlettersOnly=word.toLowerCase().replace(/\s/g,"");// Compare the string with the reversed version of the stringreturnlettersOnly===lettersOnly.split("").reverse().join("");}
For two strings to be isomorphic, all occurrences of a character in string A can be replaced with another character
to get string B. The order of the characters must be preserved. There must be one-to-one mapping for ever char of
string A to every char of string B.
`paper` and `title` would return true.
`egg` and `sad` would return false.
`dgg` and `add` would return true.
isIsomorphic("egg",'add');// trueisIsomorphic("paper",'title');// trueisIsomorphic("kick",'side');// falsefunctionisIsomorphic(firstString,secondString){// Check if the same lenght. If not, they cannot be isomorphicif(firstString.length!==secondString.length)returnfalsevarletterMap={};for(vari=0;i<firstString.length;i++){varletterA=firstString[i],letterB=secondString[i];// If the letter does not exist, create a map and map it to the value// of the second letterif(letterMap[letterA]===undefined){// If letterB has already been added to letterMap, then we can say: they are not isomorphic.if(secondString.indexOf(letterB)<i){returnfalse;}else{letterMap[letterA]=letterB;}}elseif(letterMap[letterA]!==letterB){// Eles if letterA already exists in the map, but it does not map to// letterB, that means that A is mapping to more than one letter.returnfalse;}}// If after iterating through and conditions are satisfied, return true.// They are isomorphicreturntrue;}
3.1 Implement enqueue and dequeue using only two stacks
varinputStack=[];// First stackvaroutputStack=[];// Second stack// For enqueue, just push the item into the first stackfunctionenqueue(stackInput,item){returnstackInput.push(item);}functiondequeue(stackInput,stackOutput){// Reverse the stack such that the first element of the output stack is the// last element of the input stack. After that, pop the top of the output to// get the first element that was ever pushed into the input stackif(stackOutput.length<=0){while(stackInput.length>0){varelementToOutput=stackInput.pop();stackOutput.push(elementToOutput);}}returnstackOutput.pop();}
3.2 Create a function that will evaluate if a given expression has balanced parentheses -- Using stacks
In this example, we will only consider "{}" as valid parentheses
{}{} would be considered balancing. {{{}} is not balanced
请发表评论