Repeated DNA Sequences

Find every 10-letter stretch of a DNA string that appears more than once, using a set of the stretches seen so far.

A DNA string is made of the letters A, C, G and T. Given a DNA string s, return every sequence of 10 letters in a row that appears in s more than once. Two appearances may overlap. Report each such sequence once, in any order.

Example 1
Input: s = "AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"
Output: ["AAAAACCCCC", "CCCCCAAAAA"]
Example 2
Input: s = "AAAAAAAAAAAAA"
Output: ["AAAAAAAAAA"]
Explanation: the sequence starts at positions 0, 1, 2 and 3, but is reported once.
Solution

The Idea

DNA holds the instructions of a living cell, written as a long chain of four building blocks. Biologists write them as the letters A, C, G and T, so a piece of DNA becomes a string such as AAAAACCCCCAAAAACCCCC.... Stretches that occur more than once are worth a closer look, and this problem asks for every repeated stretch of 10 letters.

Take Example 1. Its string has 32 letters, numbered 0 to 31. A stretch of 10 letters can start at position 0, 1, 2 and so on, up to position 22, where the last 10 letters begin. That makes 23 stretches. Most of them appear only once, but two of them appear twice. Look at the picture below.

The 32-letter string of Example 1. The sequence AAAAACCCCC appears at positions 0 and 10, and CCCCCAAAAA appears at positions 5 and 16. Every other 10-letter stretch appears only once.

The orange brackets above the letters mark AAAAACCCCC at 0 and AAAAACCCCC at 10: the same 10 letters, starting at two places. The teal brackets below mark CCCCCAAAAA at 5 and CCCCCAAAAA at 16. The teal stretch at 5 shares letters with both orange ones, which shows that repeats may overlap.

So how do we notice that the stretch at 10 is one we met before? Reading left to right, we reach position 10 having already passed the stretches at 0 to 9. If we write each stretch down as we pass it, we only need to ask one question at position 10: is AAAAACCCCC on the list already? It is, so it repeats.

That is the whole idea: walk along the string once, remember every 10-letter stretch you pass, and a stretch you already remember is a repeat. A frame of fixed size that moves one letter at a time like this is called a sliding window.

Solution Approach

Turning that idea into code means settling three things: how to remember the stretches so the lookup is fast, how to spot a repeat, and how to report a stretch only once when it appears three or more times. An optional last part shows a smaller way to store each stretch.

Remembering the stretches

Why not compare every stretch with every other stretch? For Example 1 that is 253 pairs of 23 stretches, and the number of pairs grows with the square of the string's length. For a string of 10,000 letters it is almost 50 million pairs, each a comparison of up to 10 letters.

A HashSet answers "have I seen this before?" in about one step, however many stretches it holds. So the code keeps a set called seen, and each stretch goes in as a 10-letter string, cut out with s.substring(i, i + 10).

Spotting a repeat

How does the code know the stretch was already there? seen.add(window) does the check and the insert at once. It returns true when the stretch is new and false when the set already holds it. A false means a repeat.

The window must stop where the string stops. The last stretch starts 10 letters before the end, so the loop runs while i + 10 <= s.length(). A string shorter than 10 letters has no stretch at all, and one of exactly 10 has a single stretch, which cannot repeat.

Reporting each sequence once

What happens in Example 2? Its 13 A's hold four stretches, and all four are AAAAAAAAAA. The first goes into seen, and the next three all get false back. If every false added the stretch to the answer, it would appear three times. So the repeats are collected in a second set, repeated, which keeps one copy of each.

Optional: a number instead of a substring

Cutting out each stretch with substring builds a new 10-letter string for every position. That can be avoided. A bit is a single 0 or 1, and two bits give four patterns, 00, 01, 10 and 11, one for each of the letters A, C, G and T. Ten letters then fit in 20 bits, a number below 1,048,576.

Moving the window one letter to the right becomes arithmetic: shift the number two bits left, put the new letter's two bits at the end, and drop the bits of the letter that fell off. In Java that is code = ((code << 2) | letter) & 0xFFFFF, where 0xFFFFF keeps only the lowest 20 bits. The set then holds numbers instead of strings. Check if a String Contains all Binary Codes of Size K uses the same rolling number.

Java Solution

The method findRepeatedDnaSequences works in these steps:

  1. First, create two empty sets of strings: seen for every stretch met so far, and repeated for the stretches met more than once.
  2. Move a start position i along the string with a loop that runs while i + 10 <= s.length(), so the last 10 letters are the last stretch.
  3. Inside the loop, cut out the stretch that starts at i as window, with s.substring(i, i + 10).
  4. Add window to seen. If add returns false, the stretch was there already, so add it to repeated.
  5. When the loop ends, copy repeated into a list and return it.

The main method runs both examples, then 11 A's, a string of exactly 10 letters, and a string of only 4.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class RepeatedDNASequences {

    public static List<String> findRepeatedDnaSequences(String s) {
        Set<String> seen = new HashSet<>();
        Set<String> repeated = new HashSet<>();      // a set, so each sequence is reported once
        for (int i = 0; i + 10 <= s.length(); i++) {
            String window = s.substring(i, i + 10);  // the 10 letters starting at i
            if (!seen.add(window)) {                 // add returns false: seen before
                repeated.add(window);
            }
        }
        return new ArrayList<>(repeated);
    }

    public static void main(String[] args) {
        System.out.println(findRepeatedDnaSequences("AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT"));
        System.out.println(findRepeatedDnaSequences("AAAAAAAAAAAAA"));   // 13 A's
        System.out.println(findRepeatedDnaSequences("AAAAAAAAAAA"));     // 11 A's
        System.out.println(findRepeatedDnaSequences("ACGTACGTAC"));      // exactly 10 letters
        System.out.println(findRepeatedDnaSequences("ACGT"));            // shorter than 10
    }
}

Running it prints:

Output
[AAAAACCCCC, CCCCCAAAAA]
[AAAAAAAAAA]
[AAAAAAAAAA]
[]
[]

The first line finds AAAAACCCCC and CCCCCAAAAA, the two sequences marked with brackets in the picture. The second line, for 13 A's, shows AAAAAAAAAA once even though seen.add returned false three times. With a list in place of the repeated set, the same input prints [AAAAAAAAAA, AAAAAAAAAA, AAAAAAAAAA].

The third line comes from 11 A's. They hold only two stretches, at positions 0 and 1, and the two share nine letters, yet they still count as a repeat. The last two lines are empty: 10 letters give one stretch with nothing to match, and 4 letters give none, so the loop never runs.

The original implementation, RepeatedDNASequences.java, is on GitHub.

Complexity

The work is one pass of the window, with one substring and one or two set operations at each position.

  • Time: O(10 × n), where n is the length of s. The loop visits about n start positions, and at each one substring copies 10 letters and the set hashes them. With the 20-bit number from the optional part, each step is a few arithmetic operations, so the time is O(n).
  • Space: O(10 × n), because seen may hold up to n - 9 different stretches of 10 letters each. repeated is never larger than seen.

Sliding Window Basics covers fixed-size windows like this one.