HackerRank Repeated String | JS Solution

HackerRank Repeated String | JS Solution

Problem

HackerRank detailed problem description can be found here.

Inputs & Outputs

/*
param {string} s
param {number} n

returns {number} Number of `a` occurances
*/

Test Cases

repeatedString('aba', 10);
repeatedString('a', 1000000);

Pseudo Code

  1. Let's figure out how many times the string s will be repeated in our algorithm without remainder and record the number in fullRepeats variable. This allows us to skip through inefficient looping over the same string s.
    For example, if we start with the following inputs s = 'aba', n = 10, we can see that 'aba' string will be repeated 3 times in full in our function ('aba-aba-aba-a') and therefore we can only count 'a's in 'aba' once and then multiply the result by the number of full string repeats countA = countA * fullRepeats or 2 * 3 = 6
  2. Now, if there was a remainder, we can loop over our sting s one more time up to that remainder
  3. Lastly, let's return the countA

JavaScript Solution

function repeatedString(s, n) {
  let fullRepeats = Math.trunc(n / s.length);
  let remainder = n % s.length;
  let countA = 0;

  for (let i = 0; i < s.length; i++) {
    if (s.charAt(i) === 'a') {
      countA++;
    }
  }

  countA = countA * fullRepeats;

  if (remainder) {
    for (let i = 0; i < remainder; i++) {
      if (s.charAt(i) === 'a') {
        countA++;
      }
    }
  }

  return countA;
}

Resources

  1. Repeated String algorithm by HackerRank
  2. Math.trunc() and charAt() by MDN Web Docs