Skip to content
DeepForgeby svx
All problems
MediumData Structuresds-081

Group Strings by Sorted Key

Problem

Group strings that are anagrams of each other, using a sorted-character key.

Two strings belong to the same group when sorting their characters yields the same key. Keep groups in order of first appearance in the input and include duplicate strings.

Return a list of groups, each sorted in ascending order.

Hint

Use the sorted characters as the dictionary key and remember the order keys first appear.

Test cases

case 1
in: [["eat","tea","tan","ate","nat","bat"]]
expected: [["ate","eat","tea"],["nat","tan"],["bat"]]
case 2
in: [[]]
expected: []
case 3
in: [["a","a"]]
expected: [["a","a"]]
case 4
in: [["ab","ba","abc"]]
expected: [["ab","ba"],["abc"]]
Starter codePython
def group_by_sorted_key(words):
    # Your code here
    pass

4 test cases · run your code against them in the editor