Search code examples
javascriptobjecthashmaphashtablerepeat

How can I solve a problem which is "a string consisting of characters A, C, G, and T. Find the longest repetition" with Map() in javascript


You are given a DNA sequence: a string consisting of characters A, C, G, and T. Your task is to find the longest repetition in the sequence. This is a maximum-length substring containing only one type of character.

I am trying to solve this problem with Map() in javascript.

My solution:



    let n='ATTCGGGA';
var reptition = function(n) {
let strToArr=n.split('');
for(let i=0; i<strToArr.length; i++)
{ 
    let map=new Map();
    map.set(strToArr[i],0);
    const iterator1 = map.values();
for (const [key, value] of map.entries()) {
    if(map.has(strToArr[i])){
     map.set(strToArr[i],iterator1.next().value+1)  
     console.log(key + ' : ' + value)
    }
}
} 


};

console.log(reptition(n));

I am trying to run a loop through all characters in a sequence and then set in Map() as a key which is characters and 1 as value to all characters. If the same character repeats then its value will be incremented by 1 and lastly, the longest repetition will be returned.

But I can't figure out how can I do this?


Solution

  • Here is a corrected impementation:

    let n = 'ATTCGGGA';
    
    var reptition = function (n) {
      let strToArr = n.split('');
      let map = new Map();
    
      let currentLetter = null;
      let currentCount = 0;
      for (let i = 0; i < strToArr.length; i++) {
        if (currentLetter === strToArr[i]) {
            currentCount++;
        } else {
            currentCount = 1;
            currentLetter = strToArr[i];
        }
        const previousCount = map.get(currentLetter) ?? 0;
        if (currentCount > previousCount) map.set(currentLetter, currentCount);
      }
      return Array.from(map.entries()).sort((prev, next) => next[1] - prev[1])[0]; 
    };
    
    console.log(reptition(n));

    You are re-declaring the new Map() on every iteration of your loop. Also you can solve this with a single iteration - not sure what the nested iterations were about.

    You can of course make the above implementation more performant, e.g. by removing the utility variables currentLetter and currentCount. Just play around a bit!