import Foundation
/// Groups an array of strings into subarrays of anagrams.
func groupAnagrams(_ words: [String]) -> [[String]] {
// Validate input
guard !words.contains(where: { $0.isEmpty }) else {
fatalError("All elements must be non-empty strings.")
}
// Dictionary to group words by their sorted character key
var anagramMap: [String: [String]] = [:]
for word in words {
let key = String(word.sorted()) // Sort characters to form the key
anagramMap[key, default: []].append(word)
}
// Return grouped anagrams as an array of arrays
return Array(anagramMap.values)
}
let arr = ["eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro"]
let result = groupAnagrams(arr)
print("Grouped anagrams:")
for group in result {
print(group)
}
/*
run:
Grouped anagrams:
["eat", "tea", "ate"]
["nat", "tan"]
["rop", "orp", "pro"]
["bat"]
*/