How to convert a sequence of strings and group all the anagrams into subsequences in Scala

1 Answer

0 votes
object AnagramGrouper {

  // Groups an array of strings into subarrays of anagrams
  def groupAnagrams(words: Seq[String]): Seq[Seq[String]] = {
    // Validate input
    if (words.exists(_.isEmpty)) throw new IllegalArgumentException("All elements must be non-empty strings.")

    // Group words by their sorted character key
    val grouped = words.groupBy(word => word.sorted)

    // Return grouped anagrams as a sequence of sequences
    grouped.values.toSeq
  }

  def main(args: Array[String]): Unit = {
    val arr = Seq("eat", "tea", "rop", "ate", "nat", "orp", "tan", "bat", "pro")

    try {
      val result = groupAnagrams(arr)
      println("Grouped anagrams:")
      result.foreach(group => println(group.mkString("[", ", ", "]")))
    } catch {
      case e: Exception => println(s"Error: ${e.getMessage}")
    }
  }
}




/*
run:

Grouped anagrams:
[bat]
[nat, tan]
[eat, tea, ate]
[rop, orp, pro]

*/

 



answered Nov 15, 2025 by avibootz
...