Javascript algorithms and data structures Flashcards
Explain the frequency counter pattern
Useful for avoiding O(N^2) with arrays and strings.
Counts frequency of specific item and add it to an object.
Good example is to check if 2 strings are anagrams of each other.
const same = function(string1, string2){
const counter1={};
const counter2={};
string1.split(‘’).forEach(letter=>{
if(counter1[letter]) counter1[letter]++;
counter1[letter]=1;
})
string2.split(‘’).forEach(letter=>{
if(counter2[letter]) counter2[letter]++;
counter2[letter]=1;
})
// then check if counter1 and counter 2 are the same
}
What is recursion?
It is when a function calls itself until a certain base case is met. The base case ensures that it doesn’t continue infinitely.
Multiple pointer pattern
Have two pointers, each referencing a given index in an array to start with. Move these pointers in a way to solve a problem.
Use a while loop