187. Repeated DNA Sequences

Sravya Divakarla
2 min readOct 18, 2023

--

I am practicing sliding window problems. A sliding window with a fixed length is when:

On each iteration you subtract the previous element from the window and add the next element to the window

In this problem:

You want to

  1. Identify each sequence of 10 through a sliding window
  2. See if that sequence was already seen in a previous window
  3. Store duplicate sequences in the resulting array

I use sets instead of maps as we only care about if the unique sequences is seen (we don’t need a key value pair as there is not info needed for value)

We also use a set for the resulting array of repeated sequences as we want UNIQUE repeated sequences. If the sequences appears 3 times we don’t want 2 of the same in the returned array. Set allows you to store unique elements only

var findRepeatedDnaSequences = function(s) {
var seqSet = new Set()
var res = new Set()
for(var i = 10 ; i < s.length; i++){
var seq = s.slice(i-10,i) // 1. Identify each sequence of 10 through a sliding window
if(seqSet.has(seq)){ // 2. See if that sequence was already seen in a previous window
res.add(seq) // 3. Store duplicate sequences in the resulting array
}else{
seqSet.add(seq)
}
}
return [...res]
};

Hope that makes sense!

Here are more types of window problems you can solve next:

--

--

No responses yet