DEV Community

Cover image for Leetcode: Valid Anagram (Kotlin)
Christopher Coffee
Christopher Coffee

Posted on • Updated on

Leetcode: Valid Anagram (Kotlin)

I will show you my approach to solving the Leetcode easy problem, Valid Anagram, using Kotlin. The problem statement is: Given two strings s and t, return true if t is an anagram of s, and false otherwise. They also give two examples shown below:

Leetcode Valid Anagram Examples

Basically, a valid anagram of another string consists of a string that contains the same characters and the same count of each character. Anytime you need to keep a count of something, using a hashmap can be considered. This is the approach I took in solving this problem.

These are the steps I took in solving this:

  1. Compare the size of both strings. If they are not equal, we do not need to do anything else and can return false.

  2. Create a HashMap with Char keys and Int values.

  3. Create character arrays of both strings.

  4. Loop through one of the character arrays and add the count of each character to the HashMap.

  5. Loop through the other character array and check if each character is in the HashMap. Decrement the count if the character is found and the count is bigger than 0. If the count is 0, return false since there is a higher count of this character.

  6. After you go through checking if every character in the second character array is in the map, this means both strings are valid anagrams.

Check out the code below:

fun isAnagram(s: String, t: String): Boolean {

    if(s.length != t.length) return false

    val map = HashMap<Char, Int>()

    val sArray = s.toCharArray()
    val tArray = t.toCharArray()

    for(c in sArray) map[c] = map.getOrDefault(c, 0) + 1

    for(c in tArray){
        var current = map.getOrDefault(c, 0)
        if(current < 1) return false
        map[c] = --current

    return true

Enter fullscreen mode Exit fullscreen mode

Leetcode Valid Anagram Submission Results

Check out the codelab version of this solution:

Check out the video version of this solution here:

Top comments (0)