progress

~/problems / Sliding window

Repeated DNA Sequences

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~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.

⭐ Bonus: comparing every window against every other window (O(n²)) still passes; a speed test on a long string earns a star at O(n) (window length 10 counts as a constant).

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: Sliding window. Grow right, shrink left while invalid; monotonic deque for window max/min.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc