Given an array of strings words, group together all words that are isomorphic to each other.
Two strings are isomorphic if the characters in one string can be replaced to get the other, where each character maps to exactly one character and no two characters map to the same character (a strict one-to-one mapping). The order of characters must be preserved.
For example, apple and offer are isomorphic because a → o, p → f, l → e and e → r. Return a list of groups, where each group contains all words sharing the same isomorphic pattern.
Function Signature
def group_isomorphic(words: list[str]) -> list[list[str]]:
Rules
-
Words of different lengths are never isomorphic.
-
A word with no isomorphic partner in the list forms a group by itself.
-
Duplicate words are kept: every copy appears in its group.
-
Return the groups in a fixed order: sort the words inside each group in ascending lexicographic order, then sort the groups in ascending order of their first word.
Constraints
-
1 <= len(words) <= 10^4
-
1 <= len(words[i]) <= 100
-
words[i]
consists of lowercase English letters only.
Examples
Input: words = ["apple", "offer", "hello", "world", "dwoom"]
Output: [["apple", "offer"], ["dwoom", "hello"], ["world"]]
"apple" maps to "offer" with a→o, p→f, l→e, e→r, and "hello" maps to "dwoom" with h→d, e→w, l→o, o→m. "world" has five distinct letters while every other word has four, so it stands alone.
Input: words = ["egg", "add", "foo", "bar", "dad"]
Output: [["add", "egg", "foo"], ["bar"], ["dad"]]
"egg", "add" and "foo" are each one letter followed by a different letter written twice. "bar" has three distinct letters and "dad" repeats its first letter at the end, so each of them is alone.
Input: words = ["ab", "aa", "xyz", "ab", "cd", "b"]
Output: [["aa"], ["ab", "ab", "cd"], ["b"], ["xyz"]]
Both copies of "ab" and the word "cd" are two distinct letters, so they form one group with the duplicate kept. "aa", "b" and "xyz" have no partner, and the groups are ordered by their first words "aa", "ab", "b", "xyz".