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: Both have pattern [1]: 'z'→'a' is +1 (wrapping), 'y'→'b' is +3, but we normalize by taking mod 26.

Constraints

  • 1 ≤ strings.length ≤ 200
  • 1 ≤ strings[i].length ≤ 50
  • strings[i] consists of lowercase English letters only

Visualization

Tap to expand
Group Shifted Strings ProblemInput Strings"abc""bcd""acf""xyz"Patterns[1,1] [1,1][2,3] [1,1]GroupsGroup 1: [1,1]"abc", "bcd", "xyz"Group 2: [2,3]Strings with same difference pattern belong to same group"abc" → "bcd" → "cde" → ... → "xyz" (all shift by +1 each step)
Understanding the Visualization
1
Input Analysis
Calculate difference pattern for each string
2
Pattern Matching
Group strings with identical patterns
3
Output
Return grouped strings as nested arrays
Key Takeaway
🎯 Key Insight: Strings that can be shifted into each other have identical character difference patterns
Asked in
Google 25 Facebook 18 Amazon 12
28.0K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen