Skip to content

Instantly share code, notes, and snippets.

@ynechaev
Created November 15, 2023 18:01
Show Gist options
  • Save ynechaev/eaae1fb0a9dda8aa059e50e503b490a1 to your computer and use it in GitHub Desktop.
Save ynechaev/eaae1fb0a9dda8aa059e50e503b490a1 to your computer and use it in GitHub Desktop.
Sherlock anagrams - Swift solution
// Given a string return a number of all possible anagrams
func sherlockAndAnagrams(s: String) -> Int {
var anagramCount = 0
var frequencyMap = [String: Int]()
// Iterate through all possible substrings
for i in 0..<s.count {
for j in i+1..<s.count + 1 {
let substring = String(s[s.index(s.startIndex, offsetBy: i)..<s.index(s.startIndex, offsetBy: j)])
let sortedSubstring = String(substring.sorted())
// Increment the count for the sorted substring in the frequency map
frequencyMap[sortedSubstring, default: 0] += 1
}
}
// Count the number of anagram pairs using the frequency map
for count in frequencyMap.values {
anagramCount += (count * (count - 1)) / 2
}
return anagramCount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment