⚡Flashcard Drill➔
NeetCode #20LC-249MediumArrays & HashingNC Algo100
← Back to All Problems

#20 · #249 · Group Shifted Strings(移位字符串分组)

📌 Problem Statement & Constraints

Given a list of strings where all strings are of the same length, group all strings that belong to the same shifting sequence. A shifting sequence is formed by rotating every character of a string by the same amount. Return the groups in any order. Constraints: 1 <= strings.length <= 200, 1 <= strings[i].length <= 50.

💡 Core Algorithmic Approaches

  1. A shift changes every character by the same amount, so the differences between consecutive characters are shift-invariant.
  2. For a string s, build the key tuple((ord(s[i]) - ord(s[i-1])) % 26 for i in 1..len-1).
  3. The modulo is essential: a -> z wraps around, so a raw difference would be -25 instead of 1.
  4. Single-character strings all produce the empty tuple and therefore group together -- which is correct, since any single character can be shifted into any other.

💻 Benchmark Python3 Implementation

class Solution:
    def groupStrings(self, strings: List[str]) -> List[List[str]]:
        from collections import defaultdict
        groups = defaultdict(list)
        for s in strings:
            # shift-invariant key: consecutive character deltas, wrapped mod 26
            key = tuple((ord(s[i]) - ord(s[i - 1])) % 26 for i in range(1, len(s)))
            groups[key].append(s)
        return list(groups.values())

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n * k) where n is the number of strings and k the string length: each string is hashed in one pass.
💾 Space Complexity
O(n * k) for the groups and the keys.

⚠️ Interview Pitfalls & Follow-ups

  • Omitting the % 26: the difference ord('a') - ord('z') is -25, which is the same shift as +1, so the keys would fail to match.
  • Using the first character as part of the key: that is exactly what a shift changes, so it must be excluded.
  • Using a list as the dict key: unhashable; wrap it in tuple.
  • Special-casing single-character strings: the empty tuple already groups them correctly, so no branch is needed.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

移位字符串分组

给定一个字符串数组 strings,将其中所有 移位字符串 组合在一起。移位字符串的定义:对字符串 s 的每个字符执行同一个「循环移位」(即每个字符都加上相同的整数 k,超过 z 则回绕到 a),若两个字符串能通过这种方式互相转换,则它们是移位字符串。例如 "abc" → "bcd" → "xyz" 属于同一组。按任意顺序返回结果列表。约束:1 ≤ strings.length ≤ 200;0 ≤ strings[i].length ≤ 200;strings[i] 仅含小写字母。

核心要点

  • 核心洞察 :移位不改变「相邻字符之间的差值」,因此把「相邻字符差值的序列」作为分组签名。
  • 差值必须取模 26 :因为字符是循环的(z 的下一位是 a), ord(s[i]) - ord(s[i-1]) 可能为负,必须写成 (a - b) % 26 才能保证 "az" 与 "ba" 落入同一组。
  • 为什么是「差值」而非「首字符 + 偏移」 :若用「把首字符平移到 a」作为规范形,需处理 26 种偏移;直接用差值序列只需一次 O(k) 计算,更简洁。
  • 单字符与空串 :长度 ≤ 1 的字符串差值序列为空元组 () ,因此它们全部归入同一组——这是正确的,因为任意单字符都可通过移位互相转换。

常见陷阱

  • 忘记对 26 取模 : ord(s[i]) - ord(s[i-1]) 在跨越 z→a 时为负(如 "az" 得到 -25),不取模会导致 "az" 与 "ba"(差值 +1)被分到不同组。这是本题第一大坑。
  • 用绝对字符值作为签名 :把每个字符平移到 0-25 后直接拼字符串,会把 "abc" 与 "bcd" 分到不同组,因为它们整体偏移不同。
  • 用列表而非元组作字典键 :list 不可哈希,会抛 TypeError。必须转成 tuple 或带分隔符的字符串。
  • 误以为单字符串不能分组 :所有单字符串差值序列都是空元组,天然归为一组,符合题意。

参考实现

class Solution:
    def groupStrings(self, strings: list[str]) -> list[list[str]]:
        groups = {}
        for s in strings:
            # 相邻字符差值(模 26)作为分组签名
            key = tuple((ord(s[i]) - ord(s[i - 1])) % 26 for i in range(1, len(s)))
            groups.setdefault(key, []).append(s)
        return list(groups.values())