Interview Question & Answer – 4

By | September 29, 2018

Question

Lilah has a string, , of lowercase English letters that she repeated infinitely many times.

Given an integer, , find and print the number of letter a’s in the first letters of Lilah’s infinite string.

For example, if the string and , the substring we consider is , the first characters of her infinite string. There are occurrences of a in the substring.

Function Description

Complete the repeatedString function in the editor below. It should return an integer representing the number of occurrences of a in the prefix of length in the infinitely repeating string.

repeatedString has the following parameter(s):

s: a string to repeat
n: the number of characters to consider

Input Format

The first line contains a single string, .
The second line contains an integer, .

Constraints

For of the test cases, .
Output Format

Print a single integer denoting the number of letter a’s in the first letters of the infinite string created by repeating infinitely many times.

Sample Input

aba
10

Sample Output

7

Explanation

The first letters of the infinite string are abaabaabaa. Because there are a’s, we print on a new line.

Sample Input

a
1000000000000

Sample Output

1000000000000

Solution

static long repeatedString(String s, long n) {
    long aCount = 0;
    long length = s.length();
    long q = n / length;
    long rem = n % length;

    String remString;
    aCount += getCount(s);
    aCount *= q;
    if (rem > 0) {
        remString = s.substring(0, (int) (rem));
        aCount += getCount(remString);
    }
    return aCount;
}

static int getCount(String string) {
    int count = 0;
    if (null == string || string.isEmpty()) {
        return count;
    }
    char[] chars = string.toCharArray();
    for (int i = 0; i < string.length(); i++) {
        if (chars[i] == 'a') {
            count++;
        }
    }
    return count;
}

Leave a Reply

Your email address will not be published. Required fields are marked *