Valid Anagram
1 min read

Valid Anagram

Given two strings s and treturn whether or not s is an anagram of t.
Note: An anagram is a word formed by reordering the letters of another word.

Ex: Given the following strings...

s = "cat", t = "tac", return true
s = "listen", t = "silent", return true
s = "program", t = "function", return false

We can use a HashTable method to determine if the string is an anagram

fun isAnagram(s: String, t: String): Boolean {
 	if (s.isEmpty() || t.isEmpty() || s.count() != t.count()) return false

        var wordMap = HashMap<Char,Int>()
        for(i in s.indices) {
            wordMap[s[i]] = wordMap.getOrDefault(s[i],0) + 1
            wordMap[t[i]] = wordMap.getOrDefault(t[i],0) - 1
        }
        for (i in wordMap.keys) {
            if(wordMap[i]!= 0) return false
        }
        return true
    }

Solution 2

To examine if t is a rearrangement of s, we can count occurrences of each letter in the two strings and compare them. Since both s and t contain only letters from a−z, a simple counter table of size 26 is suffice

   fun isAnagram(s: String, t: String): Boolean {
        if (s.isEmpty() || t.isEmpty() || s.count() != t.count()) return false
        
        val diff = IntArray(26)
        for (i in s.indices){
            diff[s[i] - 'a']++
            diff[t[i] - 'a']--
        }
        
        for (num in diff){
            if (num != 0) return false
        }
        
        return true
    }
}