Group Shifted Strings - Problem
Given an array of strings strings, group together all strings that belong to the same shifting sequence.
A shifting sequence is formed by applying shift operations on a string:
- Right shift: Replace every letter with the successive letter of the English alphabet, where 'z' is replaced by 'a'. For example, "abc" → "bcd", "xyz" → "yza"
- Left shift: Replace every letter with the preceding letter of the English alphabet, where 'a' is replaced by 'z'. For example, "bcd" → "abc", "yza" → "xyz"
Strings in the same shifting sequence can be transformed into each other through these operations. For example, "abc", "bcd", and "xyz" all belong to the same shifting sequence because:
"abc" → "bcd" → "cde" → ... → "xyz"
You may return the answer in any order.
Input & Output
Example 1 — Basic Grouping
$
Input:
strings = ["abc","bcd","acf","xyz","az","ba","a","z"]
›
Output:
[["abc","bcd","xyz"],["acf"],["az","ba"],["a"],["z"]]
💡 Note:
"abc", "bcd", "xyz" have same pattern [1,1]. "az" and "ba" have same pattern [25]. Single characters form separate groups.
Example 2 — All Same Group
$
Input:
strings = ["a","b","c"]
›
Output:
[["a","b","c"]]
💡 Note:
All single characters have empty pattern [], so they belong to same group.
Example 3 — Wraparound Pattern
$
Input:
strings = ["za","yb"]
›
Output:
[["za","yb"]]
💡 Note:
"za" has pattern [1] (z→a = +1 with wraparound), "yb" has pattern [3] (y→b = +3 with wraparound). They have different patterns so belong to different groups.
Constraints
- 1 ≤ strings.length ≤ 200
- 1 ≤ strings[i].length ≤ 50
- strings[i] consists of lowercase English letters only
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code