# Repeated Strings Hacker Rank challenge

I'm doing a hacker rank challenge with this one called "Repeated String". I attempted this challenge in my weaker language java. The goal is to print out the occurrences of the letter a. First you're given a string "aba" then a number 10. The new string generated would be abaabaabaa and you need to count the a. The solution below works but is it as simple as it should be? I've looked around and my solution looks good but still I'm terrified I'm over complicating this.

// Complete the repeatedString function below.
static long repeatedString(String s, long n) {
final long quotient = n/s.length();
final long remainder = n%s.length();
long aCount = 0;

if((s.length() == 1) && (s.charAt(0) == 'a')){
return n;
}
for(int i=0; i<s.length(); i++){
if(s.charAt(i) == 'a'){
aCount++;
}
}
aCount = aCount * quotient;
for(int i=0; i<remainder; i++){
if(s.charAt(i) == 'a'){
aCount++;
}
}
return aCount;
}

• I like the insight that you don't need to create the repeated string. However, because you are doing something other than the obvious, I would suggest that this is a case where a comment would be good to clarify that insight. Jul 5, 2019 at 7:14

If your goal is to optimize efficiency, you can do a little better by only looking at each character in the string once. The first remainder characters of the string will occur quotient + 1 times. The remaining characters will occur quotient times. So you can loop once from 0 to remainder and do some math, then loop from remainder + 1 to s.length() and do some math, and you'll have your result. It's unclear without testing whether it's faster to do the multiplication outside or to add the correct amount in your loop. Also, your short-circuit for inputs of length one is not helpful unless you expect that most of the inputs will be a single-character. It's probably safe to pull it.