acavemancoding
Published in

acavemancoding

Anagrams- Checking for frequency

Anagram with explanation

What is an Anagram?

Anagrams are by definition

“a word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.” — Oxford

In the code above we are checking to see if the letters contained in one array/string are the same as the letters in a second array or sting; there are many ways to accomplish this task, but here I use a Linear time method 0(2) to determine whether or not my two strings contain the same letters.

So to break it down, we have declared a function named anagram, this function will take two strings i named array1 and array2.

The first thing we are going to do is compare the length of the two arrays, if they are not equal we will exit the function and return false.

If true we will create an object I named “lookup”, after, we will loop through our first array and assign values to our lookup object based on our arrays index value, adding 1 for each occurrence. (i left my logs in my code so you can see how this is working).

after we have created an object the represents the values of our array we are going to loop through our second array;

First we will check for the existence of equal keys, and second we will subtract one from the value.

If we are able to exit this loop without returning false, the function will return true.

Could you have written this algorithm more efficiently? Please post below if so.
My goal with these articles is to give myself the barney style lecture I could of use to understand more easily; you can copy my code snippet below.

-Anthony

//anagram function find if arrays contain the same letters

function anagram(array1, array2){

// check for length, if length is not equal the value is false

if(array1.length !== array2.length){

console.log(“false”);

return false;

}

// creating an object to hold each letter as a key and set values to the number of times the letters occue

let lookup = {};

for(let i = 0; i < array1.length; i++){

// let the current letter equal the index value of the array

let letter = array1[i]

console.log(i, “i”)

// conditionally if the letter add 1 if letter is 0 add 1

lookup[letter] ? lookup[letter] += 1 : lookup[letter] = 1;

console.log(lookup);

}

for(let i = 0; i < array2.length; i++){

let letter = array2[i]

//if lookup object does not contain the letter return false

if(!lookup[letter]){

return false;

} else {

// else subtract 1 from the value

lookup[letter] -= 1

}

}

//end of loop if exited return true

console.log(“true”);

return true;

}

anagram(“this”, “siht”);

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store