12
Jan
2020

Hackerrank Repeated String (Javascript)

Javascript :

function repeatedString(s, n) {
    var str = "", noOfA = 0, divide = 0, modRemainder = 0, totalNoOfA = 0;
    
    //single letter arrays
    if(s.length == 1){
        if(s[0] == 'a'){
            noOfA = n;
        }else{
            noOfA = 0;
        }   
    }else if (s.length - 1 >= n){
        for(var i = 0; i < n; i++){
            if(s[i] == 'a'){
                noOfA++;
            }
        }
    }else{
        for(var i = 0; i < s.length; i++){
            if(s[i] == 'a'){
            noOfA++;
            }
        }
        divide = Math.floor(n / s.length);
        noOfA = divide * noOfA;
        modRemainder = n % s.length;
        str = s.substring(0, modRemainder);

        for(var j = 0; j < str.length; j++){
            if(s[j] == 'a'){
                noOfA++;
            }
        }
    }

    return noOfA;
}

Explanation:

At first glance, this seems like a very simple problem. Simply repeat string s for n times, then use substring to find the number of ‘a’ that appears.

This works for small numbers for n, but for a huge number (like n = 100000000), s simply cannot hold that many characters, and will throw an invalid string length error.

To get around this problem, we have to divide the problem into several parts. First, check if s is a single char string. If s only contains a single alphabet and is an ‘a’, simply assign noOfA to n, otherwise, noOfA is 0.

If s is not a single char string but the s.length is smaller than n, simply use substring to get noOfA in a loop.

Otherwise, things get a little tricky. In the first for loop, find the numbers of a that appear in s, and assign it to noOfA. Next, find the number of times s would have to be repeated in order to be greater or equal to n by doing integer division of n / s.length, and multiply noOfA by that number. Then, find the slightly extra bit of s which could be cut off ultimately, if any, by calculating n mod s.length. Assign str to the tiny bit of extra s needed to meet n size.

Finally, count the number of ‘a’ appearing in str and add it to noOfA.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *