Repeated String Hackerrank problem solution

Repeated String Hackerrank

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

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

Input Format

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

1<=|s|<=100 1<=n<=1012
For 25% of the test cases, n>=106.
Output Format

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

Sample Input 0

Sample Output 0

Explanation 0
The first n=10 letters of the infinite string are abaabaabaa. Because there are 7 a’s, we print 7 on a new line.

Sample Input 1

Sample Output 1

Explanation 1
Because all of the first n=1000000000000 letters of the infinite string are a, we print 1000000000000 on a new line.

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;

int main()
    string s;
    cin >> s;
    ll n;
    cin >> n;
    ll ans = 0;
    int A = 0;
    int B = 0;
    for (int i = 0; i < (int)s.size(); i++)
       if (s[i] == 'a') A++;
       if ((ll)i < n % (ll)s.size() && s[i] == 'a') B++;

    cout << n / (ll)s.size() * (ll)A + (ll) B << endl;
    return 0;
#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <string>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <climits>
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <numeric>
#include <sstream>
#include <string>
#include <iostream>
#include <algorithm>
#include <unordered_map>

using namespace std;

int main(){
    string s;
    cin >> s;
    string ss=s;
    long n;
    cin >> n;
    int x=s.length();
    int cou=count(s.begin(),s.end(),'a');
    long long int c=n/x;
     int p=n%x;
    string sss(s, 0, p);
    int ip=count(sss.begin(),sss.end(),'a');
    return 0;

import sys

s = raw_input().strip()
n = long(raw_input().strip())

k = s.count("a")*(n/len(s))
k += s[:n%len(s)].count("a")
print k
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(;
        String s =;
        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)

A web developer(Front end and Back end), and DBA at Currently working as Salesforce Developer @ Tech Matrix IT Consulting Private Limited. Check me

Leave a reply:

Your email address will not be published.