Data Structures19 sections · 729 units
Open in Course

Valid Anagram - Implementation

Complete solution

Here's the solution using one map:

function isAnagram(s, t)
    if length of s != length of t
        return false

    freq := empty hash map

    for each char in s
        freq[char] := freq[char] + 1  // default 0

    for each char in t
        if char not in freq or freq[char] = 0
            return false
        freq[char] := freq[char] - 1

    return true

Time: O(n)O(n). Space: O(k)O(k) where kk is the alphabet size.