目录
正在加载目录…
正在阅读专栏 Algorithms:CLRS + MIT 6.006 第 9 篇 · 共 24 篇 · 38%

Table Doubling、Amortized Analysis 与 Karp-Rabin

发布于 2026-09-18 18:27 · 最后编辑于 2026-09-18 18:27 · 版本 v2 · 字数 5,408 · 预计阅读 11 分钟 👁 14 次阅读

Algorithms:Table Doubling and Karp-Rabin

本文逐段翻译 MIT 6.006 Fall 2011 Lecture 9《Table Doubling, Karp-Rabin》,在 chaining hash table 的基础上介绍 table resizing、rehashing 与 amortized analysis,再把 hashing 应用于 string matching,推导 Karp–Rabin 和 rolling hash。

TL;DR

  • 动态 table:保持 m = Θ(n),可以让 load factor α=n/m=Θ(1),从而维持 expected O(1) hash-table operations。
  • Table doubling:table 满时把 m 加倍并 rehash 全部 items;单次 resize 是 Θ(n),但连续 n 次 insertion 的总成本是 Θ(n),所以 insertion 的 amortized cost 为 O(1)。
  • 缩容:当 n 降到 m/4 时将 table 缩小为一半,配合 doubling 可以让 insert/delete 都保持 O(1) amortized,并避免长期浪费空间。
  • Karp–Rabin:比较 pattern 与 text window 的 hash;hash 不同可以立即排除,hash 相同再做 exact comparison,避免逐窗口重新比较整个 string。
  • Rolling hash:维护 string 的 hash、长度和必要的幂;append 与 skip 都是 O(1),因此所有 text windows 可以在线性时间内更新 hash。

目录

章节说明
Lecture 9:Hashing II从 chaining hash table 继续
为什么需要 resizingtable size 与 load factor
Rehashing 与 table doubling扩容、重建与总成本
Amortized analysis摊还复杂度的含义
缩容与 resizable arraysdelete、space 与动态数组
String matchingsubstring search 的问题
Karp–Rabin algorithmhash comparison 与验证
Rolling hashappend、skip 与窗口更新
复杂度总结动态 hashing 与 string matching
小结本讲要点

Lecture 9:Hashing II

上一讲的 chaining hash table 使用:

text
h: U → {0, ..., m - 1}
α = n / m
expected cost = Θ(1 + α)

这个结论假设 simple uniform hashing,或者使用 universal hashing,并且 hash function 本身可以在 O(1) 时间内计算。如果能始终保持 m = Θ(n),就有 α = Θ(1),从而 search、insert 和 delete 都可以保持 expected O(1)。

问题是:创建 table 时通常不知道未来会存储多少 items。

text
m 太小 → load factor 太高,chains 变长,operation 变慢
m 太大 → operation 虽快,但浪费空间

解决方案是从一个 small table 开始,根据 n 动态 grow 或 shrink。

为什么需要 resizing

假设 table 当前有 m 个 slots。当 n 增加时,如果不改变 m,load factor α=n/m 会越来越大;当 n 减少时,table 又可能保留大量空 slots。

希望在整个生命周期中大致维持:

text
m = Θ(n)

但是改变 m 会改变 hash function。以 division method 为例:

text
h(k) = k mod m

当 m 改变时,旧的 h(k) 与新的 h(k) 不同,所以不能只把旧 table 复制到新 table;必须根据新 hash function 重新计算每个 item 的 slot。

Rehashing 与 table doubling

Rehashing

当 table grow 或 shrink 时,需要:

  1. 创建一个新的 table;
  2. 使用新的 m 和新的 hash function;
  3. 扫描旧 table 的所有 slots 和 chains;
  4. 把每个 item 重新 insert 到新 table。

伪代码如下:

text
Resize(T, new-m):
    T' ← empty table with new-m slots
    for each slot in T:
        for each item in that slot's chain:
            insert(T', item)
    return T'

旧 table 有 m 个 slots,存储 n 个 items,因此扫描和重新插入的成本为:

text
Θ(n + m)

如果维持 m = Θ(n),就得到 Θ(n) 的 rehashing cost。

每次只增加一个 slot 的问题

假设 table 满时只把 m 增加 1:

text
m ← m + 1

那么几乎每次 insertion 都会触发 rebuild。连续插入 n 个 items 的总成本接近:

text
Θ(1 + 2 + 3 + ... + n) = Θ(n²)

虽然每次 resize 后 table 只增加了一个 slot,但整体性能已经失去 linear growth 的优势。

Table doubling

更好的策略是 table 满时把 size 加倍:

text
m ← 2m

假设 table sizes 按如下序列变化:

text
1, 2, 4, 8, 16, ...

连续插入 n 个 items 时,rehash costs 是:

text
Θ(1 + 2 + 4 + 8 + ... + n) = Θ(n)

其中 n 可以理解为不超过最终 size 的最近一个 power of 2。普通 insert 的 Θ(1) cost 也只增加 Θ(n),所以 n 次 insertion 的总成本仍然是 Θ(n)。

注意:某几次 insertion 会触发 linear-time resize,但 resize 的次数很少,而且每次 rebuild 的规模至少翻倍。这正是 amortized analysis 要表达的现象。

Amortized analysis

amortized analysis 是 data structures 中常用的分析技术。它不是把每个 operation 都替换成平均值,而是分析一段 operation sequence 的总成本。

如果任意 k 个 operations 的总成本满足:

text
cost(sequence of k operations) ≤ k · T(n)

就称每个 operation 的 amortized cost 为 T(n)。

因此:

text
amortized O(1)

大致意味着“对所有 operations 平均后是常数”,但某一个 operation 仍然可能花费 Θ(n)。table doubling 中的 regular insertion 很快,触发 rehash 的 insertion 很慢;把整个 sequence 的成本摊开后,每次是 O(1)。

一个直观类比是支付 rent:每月支付 1500 元,相当于每天预留 50 元;某天可能发生大笔支出,但按整个周期平均仍然可控。

缩容与 resizable arrays

Hash table 的缩容

如果只在 insert 时 doubling,而永远不 shrink,经历大量 insert 后又大量 delete,table 可能远大于当前的 n:

text
n 很小,m 很大 → α 很小,但 space 浪费

一个常见策略是:当 n 降到 m/4 时,把 table 缩小为原来的一半:

text
if n ≤ m / 4:
    m ← m / 2
    rehash all items

选择 m/4 而不是 m/2 很重要。它在 grow 和 shrink 之间留出 hysteresis:一次 resize 后,必须经历足够多的 insert 或 delete 才会再次 resize,避免 n 在阈值附近来回震荡。

更完整的 table implementation 可以在 insert 和 delete 上同时获得 O(1) amortized cost;讲义指出,精细分析见 CLRS §17.4。

Resizable arrays

同样的 trick 也用于 Python list 或其他 dynamic array:

text
array 有空位时:append 直接写入
array 满时:分配更大的 array,复制旧 elements,再写入新 element

单次扩容可能复制 Θ(n) 个 elements,但如果容量按倍数增长,连续 n 次 append 的复制总数是 geometric series:

text
1 + 2 + 4 + ... + n = Θ(n)

因此:

text
list.append:O(1) amortized
list.pop:    O(1) amortized(配合合理缩容策略)

这说明 amortized analysis 不只适用于 hash table;它是很多 dynamic data structures 的核心分析工具。

String matching

给定两个 strings s 和 t,要判断 s 是否作为 substring 出现在 t 中;如果出现,还可能需要返回出现位置和出现次数。

例如:

text
s = '6.006'
t = 整个 inbox

直接算法

对 t 中每个可能的 start position,取长度为 |s| 的 substring,与 s 做 exact comparison:

python
any(s == t[i : i + len(s)]
    for i in range(len(t) - len(s)))

每次 substring comparison 最坏需要 O(|s|),可能的位置数量约为 |t| - |s|,所以总成本是:

text
O(|s| · (|t| - |s|))
= O(|s| · |t|)

当 s 和 t 长度相近时,这个成本可能是 quadratic。

问题在于相邻的 windows 高度重叠:

text
t[i : i + |s|]
t[i+1 : i+1 + |s|]

它们只有一个 character 被移出、一个 character 被加入。Karp–Rabin algorithm 利用这一点。

Karp–Rabin algorithm

Karp–Rabin 不直接比较每个 window 的全部 characters,而是比较 hash values:

text
比较 h(s) == h(t[i : i + |s|])

如果 hash values 不同,两个 strings 一定不同,可以跳过 exact comparison;如果 hash values 相同,只能说明“可能相同”,还必须进行 exact comparison 以排除 collision:

text
if h(s) == h(window):
    if s == window:
        found a match

如果 hash function 合适,hash collision 的 probability 可以很小,例如小于 1/|s|。因此每个 window 的 expected verification cost 是常数级,整体 expected time 可以写成:

text
O(|s| + |t| · cost(h))

其中 |s| 是建立 pattern hash 的成本,|t| 是遍历 text windows 的数量级。普通地从头计算每个 substring hash 需要 O(|s|),还没有改善;要达到线性时间,必须让相邻 windows 的 hash 可以快速更新。

Rolling hash

rolling hash 是一种支持窗口移动的 hash ADT。它维护一个 string x,支持:

text
r()          返回 string x 的合理 hash h(x)
r.append(c)  将 character c 加到 x 的末尾
r.skip(c)    假设 c 是 x 的第一个 character,将它从 x 的开头移除

如果 append 和 skip 都是 O(1),就可以在 O(|t|) 时间内依次计算 text 的所有 windows 的 hashes。

Karp–Rabin 的窗口流程

先建立 pattern s 的 rolling hash,以及 text 的第一个 window:

python
for c in s:
    rs.append(c)

for c in t[:len(s)]:
    rt.append(c)

if rs() == rt():
    verify_exact_match()

这部分成本为 O(|s|)。然后逐个滑动 text window:

python
for i in range(len(s), len(t)):
    rt.skip(t[i - len(s)])
    rt.append(t[i])

    if rs() == rt():
        verify_exact_match()

第二段的 hash maintenance 是 O(|t|);只有 hash match 的 windows 才需要额外 exact verification。因此总成本是:

text
O(|t|) + O(#hash matches · |s|)

在 expected collision 很少的情况下,通常接近 O(|s| + |t|)。

Rolling hash 的数值实现

设 alphabet size 为 a,例如 byte alphabet 可以取 a = 256。把 string x 看作 base a 下的 multidigit number u:

text
x = c₀ c₁ ... c_{ℓ-1}
u = ord(c₀)·a^{ℓ-1} + ord(c₁)·a^{ℓ-2} + ... + ord(c_{ℓ-1})

直接保存 u 会随着 string 长度增长,不能保证 machine-word arithmetic。选择一个通常为 large prime 的 p,只保存:

text
r = u mod p
|x|

由于 r 可以放进一个 machine word,后续 update 更快,也避免处理任意长整数。

append(c)

在末尾追加 character c 后:

text
u' = u · a + ord(c)

取模得到:

text
r' = (u · a + ord(c)) mod p
   = ((u mod p) · a + ord(c)) mod p

因此只需使用当前保存的 r = u mod p,不必恢复完整的 u:

text
r.append(c):
    r ← (r · a + ord(c)) mod p
    length ← length + 1

skip(c)

假设 c 是当前 string 的第一个 character,且当前长度为 ℓ:

text
u = ord(c) · a^{ℓ-1} + rest

移除第一个 character 后:

text
rest = u - ord(c) · a^{ℓ-1}

因此 rolling hash 可以使用:

text
r.skip(c):
    r ← (r - ord(c) · a^{length-1}) mod p
    length ← length - 1

实际实现会预先或增量维护 a^{length-1} mod p,并始终在 arithmetic 中取模。核心是:移除 front character 和追加 back character 都只需要 constant number of arithmetic operations。

复杂度总结

Operation / algorithm复杂度关键条件
普通 hash-table insertO(1) expectedα=Θ(1)
table doubling 的 resizeΘ(n) 单次必须 rehash
连续 n 次 insertΘ(n) 总计geometric growth
insertO(1) amortizedtable doubling
deleteO(1) amortized合理 shrink threshold
直接 string matchingO(len(s)·len(t))每个 window exact compare
rolling append / skipO(1)保存模 hash 与幂
Karp–Rabinexpected O(len(s)+len(t))collision probability 足够低

Karp–Rabin 的 expected bound 不是“hash 相同就一定相同”。hash collision 必须通过 exact comparison 消除;hash function 只负责让需要验证的 windows 足够少。

小结

hash table 想保持 expected O(1),需要让 table size 与 item 数量同数量级。table doubling 通过 geometric growth 将昂贵的 rehash cost 摊开,使 insertion 达到 O(1) amortized;配合在 m/4 缩容,可以同时控制 space 和 delete cost。

相同的 hashing 思路可以用于 string matching。Karp–Rabin 先比较 pattern 与每个 text window 的 hash,只有 hash match 时才做 exact comparison。rolling hash 利用相邻 windows 的高度重叠,把 append 与 skip 都降为 O(1),从而将 string matching 的 expected cost 降到接近 O(|s|+|t|)。

参考资料

← 返回列表
← 上一篇 Hashing with Chaining:冲突、Load Factor 与 Expected O(1) 下一篇 → Open Addressing 与 Cryptographic Hashing

评论 (0)

暂无评论,来留下第一条吧。
登录 或 注册 后才能发表评论