Skip to content
Problem 187 · LeetCode 187(opens in a new tab)

Repeated DNA Sequences

MediumHash tables

A DNA strand is written as a string s made of the letters A, C, G and T.

Find every stretch of exactly 10 letters that shows up at least twice in s. The stretches may overlap. List each such stretch once, in any order.

Example 1

Input:  s = "ACGTACGTACGTAC"
Output: ["ACGTACGTAC"]
Why:    it starts at index 0 and again at index 4
2 more examples and the constraints

Example 2

Input:  s = "GGGGGGGGGGGG"
Output: ["GGGGGGGGGG"]
Why:    three overlapping windows, all the same; listed once

Example 3

Input:  s = "ACGTTGCAACGT"
Output: []
Why:    its three windows are all different

Constraints

  • 1 ≤ length of s ≤ 100,000
  • Every letter of s is A, C, G or T

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Count every window as a stringO(10 · n)
  2. Rolling 2-bit codeO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 100,000 lettersVerdict
Count every window as a stringO(10 · n)
Passes; the usual answer
Rolling 2-bit codeO(n)
Best; integers, no copies

n = length of s; 10 is the window length.

Edge cases to test

  • Shorter than 10 letters. "A" or "ACGTACGTA" has no window at all; return []. A loop to len(s) − 9 must not go negative in C++ with unsigned sizes.
  • Exactly 10 letters. One window, seen once: the answer is [].
  • Overlapping copies. "GGGGGGGGGGGG" has three windows that overlap and match; it is still a repeat.
  • Seen three or more times. Report on the second sighting only, so the window is listed once.

Common mistakes

  • Using a set of results but appending on every repeat, so a window seen three times is listed twice.
  • Forgetting the mask, so the rolling code keeps old letters and never matches again.
  • Looping i < s.size() - 9 with an unsigned size in C++, which wraps around when s is shorter than 10.

How to talk through it

  1. 1Clarify. Can repeats overlap? Should a window seen three times be listed once? What if s is shorter than 10?
  2. 2Give the simple version. Count every 10-letter window in a hash map and report on the second sighting; O(10 · n).
  3. 3Use the alphabet. Four letters need 2 bits, so a window is a 20-bit number that can be updated in O(1) per letter.
  4. 4Code the rolling window. Shift, OR in the letter, mask to 20 bits; count once i ≥ 9.
  5. 5Test out loud. Run a string shorter than 10, exactly 10 letters, and one with a window seen three times.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?