Group Shifted Strings - Problem
Imagine having a secret decoder ring that can shift letters in the alphabet! In this problem, you'll work with shifting sequences of strings.
Shifting Rules:
- Right shift: Each letter becomes the next letter in the alphabet (
a→b, b→c, ..., z→a) - Left shift: Each letter becomes the previous letter in the alphabet (
z→y, y→x, ..., a→z)
For example, the string "abc" can be shifted to form an endless sequence:... ↔ "xyz" ↔ "yza" ↔ "zab" ↔ "abc" ↔ "bcd" ↔ "cde" ↔ ...
Your task: Given an array of strings, group together all strings that belong to the same shifting sequence. Two strings belong to the same group if one can be obtained from the other by applying shift operations.
Input: An array of strings strings
Output: A list of groups, where each group contains strings from the same shifting sequence
Input & Output
example_1.py — Basic Grouping
$
Input:
["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"]
›
Output:
[["acef"], ["a", "z"], ["abc", "bcd", "xyz"], ["az", "ba"]]
💡 Note:
"abc", "bcd", "xyz" form one group (each differs by +1 shift). "az" and "ba" form another group (both have single +25 shift). "acef" is alone (unique pattern). "a" and "z" are single characters (grouped together).
example_2.py — Single Group
$
Input:
["abc", "bcd", "xyz"]
›
Output:
[["abc", "bcd", "xyz"]]
💡 Note:
All three strings belong to the same shifting sequence. "abc" → "bcd" (shift +1), "bcd" → "xyz" (shift +22, which is equivalent to +22 mod 26).
example_3.py — Edge Cases
$
Input:
["a", "aa", "aaa"]
›
Output:
[["a"], ["aa"], ["aaa"]]
💡 Note:
Strings of different lengths cannot belong to the same shifting sequence, so each forms its own group.
Constraints
- 1 ≤ strings.length ≤ 300
- 0 ≤ strings[i].length ≤ 50
- strings[i] consists of lowercase English letters only
- No two strings are identical
Visualization
Tap to expand
Understanding the Visualization
1
Identify Pattern
Calculate the 'intervals' (differences) between consecutive characters
2
Create Signature
Form a unique fingerprint from these intervals
3
Group by Signature
Strings with identical signatures belong to the same shifting sequence
4
Return Groups
Each group contains strings that can be shifted to match each other
Key Takeaway
🎯 Key Insight: Strings belong to the same shifting sequence if and only if they have the same pattern of character differences between consecutive positions!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code