Solution to HackerRank’s Repeated String

Julio Santana
1 min readAug 6, 2021

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++;
}
}

return 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));
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Julio Santana
Julio Santana

Written by Julio Santana

Software Engineer. Blockchain Enthusiast

No responses yet

Write a response