~/problems / String hashing

Repeated DNA Sequences

easy ~15 min

A DNA string uses only the letters A, C, G, T. Write find_repeated_dna(s) -> list[str] returning every length-10 substring that occurs more than once in s (occurrences may overlap). List each such substring once; any order is fine.

find_repeated_dna("ACGTACGTAAACGTACGTAA")   # ["ACGTACGTAA"]  (at positions 0 and 10)
find_repeated_dna("GGGGGGGGGGG")            # ["GGGGGGGGGG"]  (positions 0 and 1 overlap)
find_repeated_dna("ACGT")                   # []

Constraints: len(s) <= 10**5. Aim for O(n) (with the window length 10 treated as a constant); comparing every window against every other window is O(n²).

Show hint

Slide a length-10 window along s and remember what you've already seen. For extra speed, each window fits in a 20-bit integer (2 bits per letter) that you can update in O(1) per step.

Topic: String hashing / Rabin-Karp. Rolling polynomial hash for O(1) substring comparison.

0:00
Ctrl ' run · Ctrl ↵ submit
esc