← All solutions

Valid Anagram

May 29, 2025 • Go •hashmap, string • easy

Problem

  • Given two strings, determine if they are anagrams of each other. You can assume the strings contain only lowercase English letters. An anagram is a rearrangement of letters — "anagram" and "nagaram" are anagrams.

Approach

  • 1. Use a hash map to count the frequency of each character in the first string. Then iterate through the second string and subtract counts. If at any point a count drops below zero, it's not a valid anagram.

Edge Cases

  • "a" vs "ab" → false
  • "rat" vs "car" → false
  • "" vs "" → true

Reflections

Go doesn't have a built-in counter or defaultdict like Python, so I had to roll my own hash map. Not a big deal, but worth noting. Felt like a pretty clean solution overall.

Go Solution

func isAnagram(s string, t string) bool {
  if len(s) != len(t) {
    return false
  }

  m := make(map[rune]int)
  for _, letter := range s {
    m[letter]++
  }

  for _, letter := range t {
    m[letter]--
    if m[letter] < 0 {
      return false
    }
  }

  return true
}

Performance

  • Runtime beats: 77%
  • Memory beats: 63%

Complexity

  • Time: O(n) Each character is processed a constant number of times, so total time is linear in the length of the input.
  • Space: O(1) At most 26 characters for lowercase input → constant space usage.
LeetCode Problem Link