5
\$\begingroup\$

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;
}
\$\endgroup\$
1
  • \$\begingroup\$ 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. \$\endgroup\$ – Josiah Jul 5 '19 at 7:14
5
\$\begingroup\$

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.

If your goal is to avoid overcomplicating things, websites like HackerRank may not be ideal. They tend to provide algorithmic challenges that reward hyper-optimized code. By their nature, those kinds of solutions will be complicated. It turns out it's hard to write an AI that will grade readable code, but easy to write one that will grade performant code. So even though readable code is much more desirable, performant code is what scores well.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ If I could, I'd give +10 to this answer for the comment about overcomplicating and unnecessary hyper-optimizing code. \$\endgroup\$ – mtj Nov 20 '18 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.