NeetCode #17LC-1427EasyArrays & HashingNC Algo100
← Back to All Problems#17 · #1427 · Perform String Shifts(字符串的左右移)
📌 Problem Statement & Constraints
You are given a string
s and a 2D array shift where shift[i] = [direction, amount]. Direction 0 means shift left by amount, direction 1 means shift right by amount. Apply all shifts and return the final string. Constraints: 1 <= s.length <= 100, 1 <= shift.length <= 100, 0 <= amount <= s.length.💡 Core Algorithmic Approaches
- Applying shifts one by one costs O(|s|) per shift. Instead, note that shifts commute and compose additively.
- Convert every shift to a signed offset: direction 0 contributes
-amount, direction 1 contributes+amount. - Sum the offsets and reduce modulo
len(s). A positive total means a net right shift. - Then perform one rotation: a right shift by
kiss[-k:] + s[:-k].
💻 Benchmark Python3 Implementation
class Solution:
def stringShift(self, s: str, shift: List[List[int]]) -> str:
total = 0
for direction, amount in shift:
total += -amount if direction == 0 else amount # left is negative
n = len(s)
total %= n # shifts are periodic
if total == 0:
return s
return s[n - total:] + s[:n - total] # one rotation⚡ Complexity Deep Dive
⏱️ Time Complexity
O(|s| + q): O(q) to accumulate the offsets and O(|s|) for the single rotation. Naively applying each shift would be O(q * |s|).
💾 Space Complexity
O(|s|) for the new string.
⚠️ Interview Pitfalls & Follow-ups
- Applying each shift separately: O(q * |s|) and much more code than summing first.
- Forgetting
% n: a total beyondnindexes out of range (or, in Python, silently produces the wrong rotation). - Sign confusion: direction 0 is left, so it contributes a negative offset when expressed as a right shift.
- Handling
total == 0with the general formula:s[n:] + s[:n]is actually correct (s[n:]is empty), but the explicit branch is clearer and avoids a needless copy.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Arrays & Hashing Problems
中文速览与面试要点
字符串的左右移
给定一个字符串 s 和一个 shift 二维数组,其中 shift[i] = [direction, amount] :direction 为 0 表示 左移 amount 位,为 1 表示 右移 amount 位。请返回经过所有移位操作后的最终字符串。约束:1 ≤ s.length ≤ 100;0 ≤ shift.length ≤ 100;shift[i].length == 2;0 ≤ amount ≤ 100。
核心要点
- 先聚合再执行(关键优化) :多次移位可以合并为一次。把所有操作折算成「净右移量」:右移 amount 记 +amount ,左移 amount 记 -amount ,求和后再对 len(s) 取模。
- 为什么可以合并 :字符串移位构成一个循环群,移位操作满足结合律与交换律,顺序不影响最终结果。
- 一次移位实现 :净右移 k 位等价于 s[-k:] + s[:-k] (把末尾 k 个字符搬到前面)。
- 取模的意义 :移位 len(s) 位等于没移,因此先对 len(s) 取模可把 k 归约到 [0, len(s))。
常见陷阱
- 逐次执行移位 :每次移位都新建字符串,总代价 O(m · n)。聚合成一次是本题的主要优化点。
- 方向映射写反 :direction 0 是 左移 、1 是 右移 。写成 0 是右移会导致结果完全相反。
- 取模前忘记处理负数 :Python 的 % 对负数返回非负结果(如 -3 % 5 == 2 ),因此 total %= n 是安全的;但在 C++/Java 中 -3 % 5 == -3 ,必须写成 ((total % n) + n) % n 。
- 漏掉 total == 0 的短路 : s[-0:] 等于整个字符串 s , s[:-0] 等于空串,拼接后仍是 s,结果恰好正确——但显式短路更清晰,且避免依赖这种巧合。
参考实现
class Solution:
def stringShift(self, s: str, shift: list[list[int]]) -> str:
total = 0
for direction, amount in shift:
total += amount if direction == 1 else -amount # 右移为正,左移为负
n = len(s)
total %= n # 归约到 [0, n)
if total == 0:
return s
return s[-total:] + s[:-total] # 右移 total 位