Valid Anagram

Leetcode#242

Problem Statement

Given two strings s and t, return true if t is an 

anagram of s, and false otherwise.

Example 1

Input: s = “anagram”, t = “nagaram”

Output: true

Example 2

Input: s = “rat”, t = “car”

Output: false

Constraints:

  • 1 <= s.length, t.length <= 5 * 104
  • s and t consist of lowercase English letters.

Follow up: What if the inputs contain Unicode characters? How would you adapt your solution to such a case?

Golang solution

func isAnagram(s string, t string) bool {
	runeMap1 := make(map[rune]int)
	runeMap2 := make(map[rune]int)

	for _, letter := range s {
		runeMap1[rune(letter)]++
	}

	for _, letter := range t {
		runeMap2[rune(letter)]++
	}

	if len(runeMap1) != len(runeMap2) {
		return false
	}

	for runeLetter, count := range runeMap1 {
		if runeMap2[rune(runeLetter)] != count {
			return false
		}
	}

	return true
}

Optimised code

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

	runeMap1 := make(map[rune]int)

	for _, letter := range s {
		runeMap1[rune(letter)]++
	}

	for _, letter := range t {
		runeMap1[rune(letter)]--
		if runeMap1[rune(letter)] < 0 {
			return false
		}
	}

	return true
}

Output

Input
s = "anagram"
t = "nagaram"

Output
true

********************
Input
s = "a"
t = "ab"

Output
false

Please visit https: https://codeandalgo.com for more such contents.

Leave a Reply

Your email address will not be published. Required fields are marked *