Java Solution for Repeated String

Overview

In this article we will see how to solve a Repeated String problem in Java. This problem is described in Hacker Rank.

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.

Example

s = ‘abcac’, n = 10

The substring we consider is abcacabcac, the first characters of the infinite string. There are 4 occurrences of a in the substring.

Code

Below is the Java solution for the above mentioned problem:

RepeatedString.java

public class RepeatedString {

    public static long repeatedString(String s, long n) {
        long len = n / s.length() ;
        long count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == 'a') {
                count++;
            }
        }
        count = count * len;
        if (n % s.length() == 0) {
            return count;
        }
        for (int i = 0; i < n % s.length(); i++) {
            if (s.charAt(i) == 'a') {
                count++;
            }
        }
        return count;
    }
}

Test

Below we will write a simple test to test the above code:

RepeatedStringTest.java

import org.junit.Test;

import static org.junit.Assert.*;

public class RepeatedStringTest {

    @Test
    public void repeatedString() {
        assertEquals(4, RepeatedString.repeatedString("abcac", 10));
        assertEquals(7, RepeatedString.repeatedString("aba", 10));
        assertEquals(1000000000000L, RepeatedString.repeatedString("a", 1000000000000L));
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: