In this post, we will solve Repeated String HackerRank Solution. This problem (Repeated String) is a part of HackerRank Algorithms series.
Task
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
a
in the substring
Input Format
The first line contains a single string, s.
The second line contains an integer, n.
Constraints
- 1 <= |s| <= 100
- 1 <= n <= 1012
- For 25% of the test cases, n <= 106.
Sample Input 0
aba
10
Sample Output 0
7
Explanation 0
The first n = 10 letters of the infinite string are abaabaabaa
. Because there are 7 a
‘s, we return 7.
Sample Input 1
a
1000000000000
Sample Output 1
1000000000000
Explanation 1
Because all of the first n = 1000000000000 letters of the infinite string are a
, we return 1000000000000.
Solution – Repeated String – HackerRank Solution
C++
#include <iostream> #include <cstring> #include <cmath> #include <cstdio> #include <vector> #include <algorithm> #include <set> #include <string> #include <map> #include <ctime> #include <cstdlib> #include <unordered_set> using namespace std; typedef long long ll; const int MaxN = 100; char s[MaxN + 1]; int main() { ll n; scanf ("%s", s); int len = (int)strlen(s); scanf ("%lld", &n); ll tot = n / len; ll as = 0; for (int i = 0; i < len; ++i) if (s[i] == 'a') ++as; ll res = tot * as; for (int i = 0; i < n % len; ++i) if (s[i] == 'a') ++res; printf ("%lld", res); }
Python
#!/bin/python3 import sys def repeatedString(s, n): return s.count('a') * (n//len(s)) + s[:n%len(s)].count('a') if __name__ == "__main__": s = input().strip() n = int(input().strip()) result = repeatedString(s, n) print(result)
Java
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String s = in.next(); long n = in.nextLong(); long num = n/s.length(); long rem = n%s.length(); long ans = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i)=='a') { ans += num; if (i < rem) ans++; } } System.out.println(ans); } }
Note: This problem (Repeated String) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.