Repeated DNA Sequences LeetCode Solution

Last updated on October 5th, 2024 at 09:10 pm

Here, We see Repeated DNA Sequences LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Depth-First Search, Tree

Companies

Microsoft

Level of Question

Medium

Repeated DNA Sequences LeetCode Solution

Repeated DNA Sequences LeetCode Solution

Problem Statement

The DNA sequence is composed of a series of nucleotides abbreviated as ‘A’, ‘C’, ‘G’, and ‘T’.

  • For example, “ACGAATTCCG” is a DNA sequence.

When studying DNA, it is useful to identify repeated sequences within the DNA.

Given a string s that represents a DNA sequence, return all the 10-letter-long sequences (substrings) that occur more than once in a DNA molecule. You may return the answer in any order.

Example 1:
Input: s = “AAAAACCCCCAAAAACCCCCCAAAAAGGGTTT”
Output: [“AAAAACCCCC”,”CCCCCAAAAA”]

Example 2:
Input: s = “AAAAAAAAAAAAA”
Output: [“AAAAAAAAAA”]

1. Repeated DNA Sequences Leetcode Solution C++

class Solution {
public:
    vector<string> findRepeatedDnaSequences(string s) {
        unordered_map<size_t,int> MP;
        hash<string> hash_fn;
        vector<string> ret;
        
        for(int i = 0; i < int(s.size()) - 9; ++i)
            if(MP[hash_fn(s.substr(i,10))]++ == 1 )
               ret.push_back(s.substr(i,10));
               
      return ret;        
    }
};

2. Repeated DNA Sequences Leetcode Solution Java

class Solution {
    public List<String> findRepeatedDnaSequences(String s) {
        Set seen = new HashSet(), repeated = new HashSet();
        for (int i = 0; i + 9 < s.length(); i++) {
            String ten = s.substring(i, i + 10);
            if (!seen.add(ten))
                repeated.add(ten);
        }
        return new ArrayList(repeated);
    }
}

3. Repeated DNA Sequences Solution JavaScript

var findRepeatedDnaSequences = function(s) {
    let curr = s.slice(0, 10);
    const seen = new Set([curr]);
    const res = new Set();
    for(let i = 10; i < s.length; i++) {
        curr = curr.slice(1) + s[i];
        if(seen.has(curr)) res.add(curr);
        seen.add(curr);
    }
    return [...res];
};

4. Repeated DNA Sequences Solution Python

class Solution(object):
    def findRepeatedDnaSequences(self, s):
        sequences = collections.defaultdict(int)
        for i in range(len(s)):
            sequences[s[i:i+10]] += 1
        return [key for key, value in sequences.iteritems() if value > 1]
Scroll to Top