Skip to main content

🟩 Valid Anagram (#242)

📋 Problem Statement

Given two strings s and t, return true if the two strings are anagrams of each other, otherwise return false.

An anagram is a string that contains the exact same characters as another string, but the order of the characters can be different.

💡 Examples

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 * 10^4
  • s and t consist of lowercase English letters.

🐍 Solution: Python

Approach 1: Using Sorting

Time Complexity: O(n log n) | Space Complexity: O(1)

def is_anagram(s, t):
return sorted(s) == sorted(t)

Approach 2: Using Hash Table

Time Complexity: O(n) | Space Complexity: O(n)

def is_anagram(s, t):
return Counter(s) == Counter(t)

🔵 Solution: Golang

Approach 1: Sorting

Time Complexity: O(n log n) | Space Complexity: O(1)

func isAnagram(s, t string) bool {
return sorted(s) == sorted(t)
}

Approach 2: Hash Table

Time Complexity: O(n) | Space Complexity: O(n)

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

countS, countT := make(map[rune]int), make(map[rune]int)
for i, ch := range s {
countS[ch]++
countT[rune(t[i])]++
}

for k, v := range countS {
if countT[k] != v {
return false
}
}
return true
}

📚 References