Repeated String HackerRank

 public static long repeatedString(String s, long t) {

        
        
        long n=s.length();
       
        long count=0l;
        for(int i=0;i<n;i++){
            if(s.charAt(i)=='a'){
                count++;
            }
        }
       
        long q=t/n;
        count=q*count;
        long r=t%n;
        
        for(int i=0;i<(int)r;i++){
            if(s.charAt(i)=='a'){
                count++;
            }
        }
      
        return count;
    }

Approach:
Here first for the input string we will calculate the number of a's (store in long l).
Then we will see how many times the same string will be covered in the input length
(long c=dividing input length by l) and we will get the number of a's
till now by multiplying c with l (m=c*l). Now by applying modulus operation
(long r=input length% l). Later traversing up to r we will see if the character is a
then m value will increase. Hence we will return this value of m.

Space: O(1)
Time:O(length of input string)

Thanks for Reading.😇

Comments

Popular posts from this blog

Solutions Of Practice Questions Dated 01-06-2022

CODEFORCES SPY DETECTED ROUND 713

Maximum Winning Score Geeks For Geeks