• + 0 comments

    Solution in TypeScript:

    function repeatedString(s: string, n: number): number {
        const sLen = s.length;
        // use regex to calculate the count of a's in s
        const aCount = (s.match(/a/g) || []).length;
        // how many times is the lenght of s in n
        const repCount = Math.trunc(n / sLen);
        // how many characters needs to be added so the repeated string's length matches n
        const remainder = n % sLen;
        // get a substring with a length equal to the remainder number
        const remainderSubstring = s.substring(0, remainder);
        // how many a's are present in the substring
        const aCountInSubstring =  (remainderSubstring.match(/a/g) || []).length;
        // result is the count of a's in the times needed to be repeated + the ones in the remainder substring
        return repCount * aCount + aCountInSubstring;
    }