Skip to content

Instantly share code, notes, and snippets.

@shettayyy
Last active May 1, 2020 12:27
Show Gist options
  • Save shettayyy/5e11236228d7ae881a1154338b5fa328 to your computer and use it in GitHub Desktop.
Save shettayyy/5e11236228d7ae881a1154338b5fa328 to your computer and use it in GitHub Desktop.
Given two strings, write a function to determine if the second string is an anagram of the first. An anagram is a word, phrase, or name formed by rearranging the letters of another. We solve it using the frequency counter algorithm to find the valid anagram
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
// frequency counter - valid anagram
// Given two strings, write a function to determine if the second string is an anagram of the first.
// An anagram is a word, phrase, or name formed by rearranging the letters of another]
function validAnagram(str1, str2){
const frequencyCounter = {};
for(let char of str1) {
frequencyCounter[char] = (frequencyCounter[char] || 0) + 1;
}
for(let char of str2) {
if(frequencyCounter[char]) {
if(frequencyCounter[char] === 1) {
delete frequencyCounter[char];
} else {
frequencyCounter[char] -= 1;
}
}
}
return !Object.keys(frequencyCounter).length;
}
console.log(validAnagram('str1', 'str111'));
</script>
<script id="jsbin-source-javascript" type="text/javascript">// frequency counter - valid anagram
// Given two strings, write a function to determine if the second string is an anagram of the first.
// An anagram is a word, phrase, or name formed by rearranging the letters of another]
function validAnagram(str1, str2){
const frequencyCounter = {};
for(let char of str1) {
frequencyCounter[char] = (frequencyCounter[char] || 0) + 1;
}
for(let char of str2) {
if(frequencyCounter[char]) {
if(frequencyCounter[char] === 1) {
delete frequencyCounter[char];
} else {
frequencyCounter[char] -= 1;
}
} else {
return false;
}
}
return !Object.keys(frequencyCounter).length;
}
console.log(validAnagram('str1', 'str111'));</script></body>
</html>
// frequency counter - valid anagram
// Given two strings, write a function to determine if the second string is an anagram of the first.
// An anagram is a word, phrase, or name formed by rearranging the letters of another]
function validAnagram(str1, str2){
const frequencyCounter = {};
for(let char of str1) {
frequencyCounter[char] = (frequencyCounter[char] || 0) + 1;
}
for(let char of str2) {
if(frequencyCounter[char]) {
if(frequencyCounter[char] === 1) {
delete frequencyCounter[char];
} else {
frequencyCounter[char] -= 1;
}
} else {
return false;
}
return !Object.keys(frequencyCounter).length;
}
console.log(validAnagram('str1', 'str111'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment