Created
November 21, 2023 09:42
-
-
Save Robogeek95/5714fe91d8ad60d284bd87b0d79ba5d6 to your computer and use it in GitHub Desktop.
Algorithm to check if two strings are anagrams
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function validAnagram(sa, sb) { | |
if (sa.length !== sb.length) { | |
return false; | |
} | |
const charCount = {}; | |
for (let i = 0; i < sa.length; i++) { | |
charCount[sa[i]] = (charCount[sa[i]] || 0) + 1; | |
charCount[sb[i]] = (charCount[sb[i]] || 0) - 1; | |
if (charCount[sa[i]] < 0 || charCount[sb[i]] > 0) { | |
return false; | |
} | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This algorithm determines whether two given strings, sa and sb, are valid anagrams of each other. An anagram is a word or phrase formed by rearranging the letters of another.
The algorithm uses a character count approach to efficiently check whether two strings are anagrams by comparing the counts of characters in both strings. If the lengths are different or if the character counts deviate during the iteration, the function returns false; otherwise, it returns true.
Explanation of the algorithm:
The first step is to check if the lengths of the two input strings are equal. If they are not, the function returns false because strings of different lengths cannot be anagrams.
Character Count Object:
The algorithm uses an object called charCount to keep track of the count of each character in the strings.
Character Counting Loop:
The algorithm iterates through each character in the input strings using the variable i. For each character in sa, it increments the count in the charCount object, and for each character in sb, it decrements the count.
The expression (charCount[sa[i]] || 0) is used to handle the case when the character has not been encountered yet. If it's undefined (or falsy), it defaults to 0 (initializes it).
Check for Anagram Conditions:
Inside the loop, it checks if the count of a character in either string becomes negative or positive. If at any point the count becomes negative for a character in sa or positive for a character in sb, the strings are not anagrams, and the function returns false.
Return Result:
If the loop completes without returning false, it means that both strings have the same characters with the same counts, and the function returns true, indicating that the strings are valid anagrams.