⚡Flashcard Drill➔
NeetCode #135LC-2381MediumArrays & Hashing
← Back to All Problems

#135 · #2381 · Shifting Letters II(字母移位 II)

📌 Problem Statement & Constraints

You are given a lowercase string s and a list of shifts, each shifts[i] = [start_i, end_i, direction_i]. Direction 1 shifts the letters in s[start..end] forward by 1 in the alphabet (wrapping z to a); direction 0 shifts them backward. Return the final string. Constraints: 1 <= s.length <= 5 * 10^4, 1 <= shifts.length <= 5 * 10^4.

💡 Core Algorithmic Approaches

  1. Applying each shift directly is O(n * q), far too slow at these limits.
  2. Use a difference array over the string indices: add +1 at start and -1 at end + 1 for a forward shift, and the opposite for a backward shift.
  3. Then take a running prefix sum to obtain the net shift at each index.
  4. Finally apply the net shift to each character with modulo 26. This makes the whole thing O(n + q).

💻 Benchmark Python3 Implementation

class Solution:
    def shiftingLetters(self, s: str, shifts: List[List[int]]) -> str:
        n = len(s)
        diff = [0] * (n + 1)
        for start, end, d in shifts:
            v = 1 if d == 1 else -1
            diff[start] += v               # range start
            diff[end + 1] -= v             # one past the range end
        res = []
        cur = 0
        for i in range(n):
            cur += diff[i]                 # net shift at index i
            res.append(chr((ord(s[i]) - 97 + cur) % 26 + 97))
        return "".join(res)

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n + q): building the difference array is O(q) and applying it is O(n).
💾 Space Complexity
O(n) for the difference array (or O(1) extra beyond the output if the string is built in place).

⚠️ Interview Pitfalls & Follow-ups

  • Applying each shift character by character: O(n * q) = 2.5 * 10^9 operations, which will time out.
  • Forgetting the + 1 on the end index: the difference array marks the range as [start, end] inclusive, so the decrement goes at end + 1. Off by one here silently corrupts every character after the range.
  • Not taking the modulo of a negative shift: Python's % returns a non-negative result for a positive modulus, so (x - 5) % 26 is correct without extra handling.
  • Sizing diff as n instead of n + 1: writing at end + 1 would index out of range when end == n - 1.
⚡
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

中文速览与面试要点

字母移位 II

给你一个小写英文字母组成的字符串 s 和一个二维整数数组 shifts,其中 shifts[i] = [starti, endi, directioni] 。对于每个 i,将 s 中从下标 starti 到 endi(两者都包含)的所有字母都进行移位:若 directioni == 1,则 正向 移位(字母表中后移一位);若 directioni == 0,则 反向 移位(前移一位)。字母是循环的,即 z 正向移位变成 a,a 反向移位变成 z。返回经过所有移位操作后的最终字符串。约束:1 ≤ s.length ≤ 5 × 10^4;1 ≤ shifts.length ≤ 5 × 10^4;0 ≤ starti ≤ endi &lt; s.length;directioni 为 0 或 1。

核心要点

  • 差分数组(标准解) :对每个区间移位操作,用差分数组在 O(1) 内记录 diff[l] += v 、 diff[r+1] -= v ,其中正向移位 v = 1、反向 v = −1。
  • 还原累积移位量 :从左往右对 diff 做前缀和,得到每个位置需要移位的 净量 。
  • 应用移位 : chr((ord(c) - 97 + net) % 26 + 97) 。Python 的 % 保证结果非负,因此无需特判负数。
  • 为什么不用暴力 :对每个操作遍历其区间是 O(q · n),q 与 n 均可达 5 × 10^4,总操作数可达 2.5 × 10^9,必然超时。差分把「区间更新」降为 O(1),总复杂度 O(n + q)。

常见陷阱

  • 差分数组只开 n 位 :当 r == n - 1 时 diff[r + 1] 会越界。必须开 n + 1 位。
  • 把方向映射搞反 :direction 为 1 是 正向 (+1),为 0 是 反向 (−1)。写反会得到完全相反的结果。
  • 对每个操作暴力遍历区间 :O(q · n) 必然超时。差分是本题的核心。
  • 担心负数取模 :Python 的 % 对负数返回非负结果(如 -1 % 26 == 25 ),因此 (ord(c) - 97 + net) % 26 安全;在 C++/Java 中必须加 26 修正。
  • 忘记差分是「先加后减」而非「先减后加」 :标准形式是 diff[l] += v; diff[r+1] -= v 。

参考实现

class Solution:
    def shiftingLetters(self, s: str, shifts: list[list[int]]) -> str:
        n = len(s)
        diff = [0] * (n + 1)              # 多开一位,便于处理 r == n-1
        for l, r, d in shifts:
            v = 1 if d == 1 else -1
            diff[l] += v
            diff[r + 1] -= v

        res = []
        net = 0
        for i, c in enumerate(s):
            net += diff[i]                # 前缀和 = 该位置的净移位量
            res.append(chr((ord(c) - 97 + net) % 26 + 97))
        return ''.join(res)