Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,923 questions

51,856 answers

573 users

How to convert an array of strings and group all the anagrams into subarrays in Swift

1 Answer

0 votes
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"]
 
*/

 



answered Nov 15, 2025 by avibootz
...