HackerRank Problem #1
Repeated String
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.
Example
s = ‘abcac’
n = 10
The substring we consider is abcacabcac, the first 10 characters of the infinite string. There are 4 occurrences of a in the substring.
Function Description
Complete the repeatedString function in the editor below.
repeatedString has the following parameter(s):
- s: a string to repeat
- n: the number of characters to consider
Returns
- int: the frequency of
ain the substring
Input Format
The first line contains a single string, s.
The second line contains an integer, n.
Get riaevnt’s stories in your inbox
Join Medium for free to get updates from this writer.
Constraints
- 1≤ |s| ≤100
- 1≤n≤10¹²
- For 25% of the test cases, n≤10⁶ .
Sample Input
Sample Input 0
aba
10Sample Output 0
7Explanation 0
The first n=10 letters of the infinite string are abaabaabaa. Because there are 7a's, we return 7.
Sample Input 1
a
1000000000000Sample Output 1
1000000000000Explanation 1
Because all of the first n = 1000000000000 letters of the infinite string are a, we return 1000000000000.
Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'repeatedString' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
* 1. STRING s
* 2. LONG_INTEGER n
*/
public static long calculateAinString(String s, long size){
long result=0;
for(int i=0; i<size; i++){
if(s.charAt(i) == 'a'){
result = result+1;
}
}
return result;
}
public static long repeatedString(String s, long n) {
// Write your code here
int sSize = s.length();
long aInTotal = 0;
//a in a string
long aInString = calculateAinString(s, sSize);
if(n>sSize){
long kelipatan = n/sSize;
aInTotal =+ aInString*kelipatan;
long sisa = n-(kelipatan*sSize);
long aInSisa = calculateAinString(s, sisa);
aInTotal = aInTotal + aInSisa;
} else{
aInTotal = calculateAinString(s, n);
}
System.out.println("aInTotal: "+aInTotal);
return aInTotal;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
String s = bufferedReader.readLine();
long n = Long.parseLong(bufferedReader.readLine().trim());
long result = Result.repeatedString(s, n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
bufferedReader.close();
bufferedWriter.close();
}
}






