Skip to content

Valid Anagram

Easy

The problem

Given two words s and t, return true if t can be made by rearranging the letters of s (using every letter exactly once), otherwise return false.

  • Example 1
    Input: s = "listen", t = "silent"
    Output: true

    Both words have the same letters: e, i, l, n, s, t.

  • Example 2
    Input: s = "rat", t = "car"
    Output: false

    The word "rat" has a t, but "car" has a c instead.

  • Example 3
    Input: s = "aab", t = "abb"
    Output: false

    Same kinds of letters, but "aab" has two a's and "abb" has only one.

Limits
  • 1 ≤ s.length, t.length ≤ 50,000
  • s and t contain only lowercase letters a to z

Write it in Go. Try for about 20 minutes on paper first, then open one hint at a time.

Try it here

Write Go. Common packages like fmt and sort are imported for you. Keep the function name and inputs the same.

Hints, one at a time

Nudge

Two words are anagrams when every letter appears the same number of times.

The idea

Count letters of the first word, subtract for the second, and check that every count is zero (or compare two count arrays of size 26).

Target: O(n) time, O(1) space for lowercase letters

Go function shape
func isAnagram(s string, t string) bool
Reference solution

Tested with go test. Try it yourself first, then compare.

// IsAnagram: same letters, same counts. Count up for s, down for t.
func IsAnagram(s, t string) bool {
	if len(s) != len(t) {
		return false
	}
	var count [26]int
	for i := 0; i < len(s); i++ {
		count[s[i]-'a']++
		count[t[i]-'a']--
	}
	for _, c := range count {
		if c != 0 {
			return false
		}
	}
	return true
}