Created
October 12, 2019 02:49
-
-
Save kirkdrichardson/b442b5989a0e1066577d30d1f6c6993f to your computer and use it in GitHub Desktop.
Frequency Counter Pattern in Dart - anagram challenge
This file contains 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
/** | |
* | |
* Frequency Counter Pattern in Dart - anagram challenge | |
* | |
* Problem Description: | |
* | |
* Given two strings, write a function to determine if the second string is an anagram | |
* of the first. Do not worry about whitespace or non-alphanumeric characters. | |
* | |
* */ | |
// See live at https://dartpad.dartlang.org/b442b5989a0e1066577d30d1f6c6993f | |
void main() { | |
// Test cases | |
print("Test 1: ${assertBool(false, isAnagram('aww', 'ape'))}"); | |
print("Test 2: ${assertBool(false, isAnagram('an', 'app'))}"); | |
print("Test 3: ${assertBool(true, isAnagram('apple', 'plepa'))}"); | |
print("Test 4: ${assertBool(true, isAnagram('race', 'crae'))}"); | |
print("Test 4: ${assertBool(true, isAnagram('ppppp', 'ppppp'))}"); | |
print("Test 5: ${assertBool(true, isAnagram('', ''))}"); | |
} | |
// Method to return boolean if anagram | |
bool isAnagram(String s1, String s2) { | |
if (s1.length != s2.length) return false; | |
Map<String, int> charCount = Map(); | |
// One iteration through first array, O(n). | |
for (String char in s1.split('')) { | |
// Update the map by incrementing or adding cnt value for character. | |
charCount.update(char, (cnt) => ++cnt, ifAbsent: () => 1); | |
} | |
// One iteration through second array, O(n). | |
for (String c in s2.split('')) { | |
// Make sure key exists. If not, early return. | |
if (!charCount.containsKey(c)) return false; | |
// Decrement the count and get the updated value. | |
int updatedCount = charCount.update(c, (cnt) => --cnt); | |
// If the count is negative, the second word had more instances of char. | |
if (updatedCount < 0) return false; | |
} | |
// Only an anagram could make it this far 🎼🎼🎼🎼 | |
return true; | |
} | |
String assertBool(bool b1, bool b2) => b1 == b2 ? 'PASS' : 'FAIL'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment