
Valid Anagram
First Solution using a Dictionary
Approach
First, the function checks if the lengths of the two strings s and t are equal. if not, the fucntion returns false as the two strings cannot be anagrams if they have diffrent lengths.
Then, the function creates an empty dictionary to store the frequency of each character in s. it loops through every character in s and increements the frequency of the character in the dictionary by 1.
Next, the function loops through every character in t. For each character, it checks if the caracter exists in the dictionary and has a frequency greater than 0. if so, it decrements the frequency of the character in thre dictionary. if not, the finction returns false as the two strings cannot be anagrams.
if the function reaches the end of the t loop without returning false, it means that all characters in t are found in s and have the same frequency. Therefore, the function returns true as the two strings are anagrams.
class Solution {
func isAnagram(_ s: String, _ t: String) -> Bool {
guard s.count == t.count else { return false }
var dict: Dictionary<Character, Int> = [:]
for ch in s {
dict[ch, default: 0] += 1
}
for ch in t {
if let count = dict[ch], count > 0 {
dict[ch] = count - 1
} else { return false }
}
return true
}
}Complexity
This approach has a time complexity of O(n), where n is the length of the input strings.
The Second solution using String sorting
Time - complexity: O(n log n)
class Solution {
func isAnagram(_ s: String, _ t: String) -> Bool {
s.sorted() == t.sorted()
}
}The Third solution using AsciiValue
class Solution {
func isAnagram(_ s: String, _ t: String) -> Bool {
guard s.count == t.count else { return false }
let sCharCount = getCharacterCount(s)
let tCharCount = getCharacterCount(t)
return sCharCount == tCharCount
}
private func getCharacterCount(_ str: String) -> [Int] {
var charCount = Array(repeating: 0, count: 26)
let asciiValue = Character("a").asciiValue ?? 0
for char in str.utf8 {
charCount[Int(char - asciiValue)] += 1
}
return charCount
}
}