NeetCode #126LC-187MediumArrays & Hashing
← Back to All Problems#126 · #187 · Repeated DNA Sequences(重复的 DNA 序列)
📌 Problem Statement & Constraints
The DNA sequence is composed of
'A', 'C', 'G' and 'T'. Given a string s representing a DNA sequence, return all 10-letter-long substrings that occur more than once. Constraints: 1 <= s.length <= 10^5.💡 Core Algorithmic Approaches
- Slide a window of length 10 across
sand record each distinct substring in a hash set. - The first time a substring is seen, add it to
seen; the second time, add it to the result set. - Using a set for the result deduplicates substrings that occur three or more times.
- The number of windows is
n - 9, and each window costs O(1) to hash (a constant length of 10), so the total is O(n).
💻 Benchmark Python3 Implementation
class Solution:
def findRepeatedDnaSequences(self, s: str) -> List[str]:
if len(s) < 10:
return []
seen = set()
repeated = set()
for i in range(len(s) - 9): # windows of exactly length 10
sub = s[i:i + 10]
if sub in seen:
repeated.add(sub) # second sighting
else:
seen.add(sub)
return list(repeated)⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n) with a constant window length: n - 9 windows, each hashed in O(1) because the length is fixed at 10.
💾 Space Complexity
O(n) for the seen set in the worst case.
⚠️ Interview Pitfalls & Follow-ups
- Using
range(len(s) - 10): the last window would be missed; the correct bound islen(s) - 9. - Returning duplicates without deduplication: a substring occurring three times would appear twice in the output; hence the separate result set.
- Appending to a list on every second sighting: same issue, and it also loses the set's O(1) membership test.
- Encoding the substrings as integers for speed: a legitimate optimisation (2 bits per base), but unnecessary given the constant window length.
⚡
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
中文速览与面试要点
重复的 DNA 序列
DNA 序列由一系列核苷酸组成,缩写为 A、C、G 和 T。例如,"ACGAATTCCG" 是一个 DNA 序列。在研究 DNA 时,识别 DNA 中的重复序列非常有用。给定一个表示 DNA 序列的字符串 s,返回所有在 DNA 分子中出现 不止一次 的长度为 10 的序列。你可以按任意顺序返回答案。约束:0 ≤ s.length ≤ 10^5;s[i] 为 A、C、G 或 T。
核心要点
- 定长窗口 + 哈希集合(标准解) :遍历所有长度为 10 的子串,用 seen 记录出现过的,用 res 记录重复出现的(用集合去重)。
- 为什么需要两个集合 : seen 判断「是否出现过」, res 保证同一子串只被输出一次(可能出现 3 次以上)。
- 复杂度 :窗口数 O(n),每个子串切片 O(10) = O(1),总 O(n)。
- 进阶优化 · 位编码滚动哈希 :把 4 种核苷酸用 2 位表示(A=00、C=01、G=10、T=11),则长度 10 的子串恰好是 20 位整数。用滚动方式更新(左移 2 位、去高位、加新位),可避免每次切片,且哈希键是整数,速度显著提升。
常见陷阱
- 只用一个集合 :无法区分「首次出现」与「重复出现」,会把所有子串都当成结果。必须用两个集合。
- 遍历范围写成 range(len(s) - 10) :会漏掉最后一个窗口。正确范围是 range(len(s) - 9) (或 len(s) - 10 + 1 )。
- 结果不去重 :若某子串出现 3 次,朴素写法会把它加入两次。必须用集合去重。
- 忘记处理长度小于 10 的输入 :切片会返回空串或短串,需提前返回空列表。
参考实现
class Solution:
def findRepeatedDnaSequences(self, s: str) -> list[str]:
if len(s) < 10:
return []
seen, res = set(), set()
for i in range(len(s) - 9):
sub = s[i:i + 10]
if sub in seen:
res.add(sub) # 重复出现 -> 加入结果(set 自动去重)
else:
seen.add(sub)
return list(res)
# 位编码滚动哈希版本(更快,键为 20 位整数):
# code = {'A': 0, 'C': 1, 'G': 2, 'T': 3}
# mask = (1 << 20) - 1 # 保留低 20 位
# cur = 0
# for i, c in enumerate(s):
# cur = ((cur << 2) | code[c]) & mask
# if i >= 9:
# if cur in seen: res.add(s[i-9:i+1])
# else: seen.add(cur)