Skip to content
BytePatterns

Group Words by Letter Shift

MediumHash Tables#canonical-key#hash-map#grouping~20m

Problem

A cipher tool shifts every letter of a word forward by the same amount, wrapping from z back to a, so "abc" can become "bcd" or "xyz". Given a list of lowercase words, group together the words that can be shifted into one another. Return the groups in the order their first word appears in the input, and keep the words inside each group in input order. There can be up to 10,000 words of up to 50 letters each.

Examples

Input:  words = ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
Output: [["abc", "bcd", "xyz"], ["acef"], ["az", "ba"], ["a", "z"]]
Why:    "az" shifted by one becomes "ba", since z wraps round to a
Input:  words = ["dog", "eph", "cat"]
Output: [["dog", "eph"], ["cat"]]
Input:  words = []
Output: []
Why:    edge case, nothing to group

Hints

0 / 3

Stuck on the idea rather than the code? Group Anagrams covers it.