Solution to HackerRank’s Repeated String

Here is the problem:

There is a string, S, of lowercase English letters that is repeated infinitely many times. Given an integer, n , find and print the number of letter a's in the first n letters of the infinite string.

https://www.hackerrank.com/challenges/repeated-string/

The substring we consider is ‘abcacabcac’, the first 10 characters of the infinite string. There are occurrences of a in the substring. Ex s=’abcac’, n=10

My Solution:

This one can be reduced to the next formulas:

numberOfRepetOfSInN = n / size(s)

partOfIncompleteSInN = n % size(s)

totalA = numberOfRepetOfSInN * amountOfA(s) + amountOfA(s, partOfIncompleteSInN)

And then we are only pending to define the function amountOfA(string, int) that will find how many ‘a’ there are up to position int

private static int amountOfA(String totalString, char charToCount, int to) {
int total = 0;

for(int i = 0; i < to; i++) {
if(totalString.charAt(i) == charToCount) {
total++;
}
}

}
public static long repeatedString(String s, long n) {
int sLenght = s.length();

return (n / sLenght) * howMany(s, 'a', sLenght) + howMany(s, 'a', (int)(n % sLenght));
}

Software Engineer. Blockchain Enthusiast

More from Julio Santana

Software Engineer. Blockchain Enthusiast