Repeated String

Parag Naik
2 min readApr 6, 2021

Problem Statement:-
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” in string “s” in the first “ n” letters of the infinite string.

Photo by Crawford Jolly on Unsplash

Solution:-
Interesting hackerrank problem where we need to find the letter “a” in first “n“ letters a given string which is repeated infinitely. Lets move towards the code.In the first if-condition we will consider an edge case where the string has only single letter which is “a”,as it is a single letter and it’s “a” it will repeat exactly “n” number of times.

def repeatedString(s, n):
if len(s)==1 and s=="a":
return n
else:
b=s.count("a")
x=n//len(s)
z=b*x
remaining=n-(x*len(s))
y=s[:remaining].count("a")
return z+y

The else-condition is where the entire problem lies,first we will count the number of “a” in the given string and store the count in variable “b”.The we will calculate the minimum times the string will be repeated for first “n” number of variable by dividing “n” with the length of the string and store it in “x”. Then we will multiply the number of “a”s in string with x and store it in “z”.Now we will find the remaining part which is nothing but the difference between “n” and product of “x” and the length of “s”. Then we will count the number of “a” in the remaining part and store it in y. In next line we will return the sum of z and y.

Conclusion:-
All you need in this life is ignorance and confidence, and then success is sure”. As per the famous quote all we need to ignore the negativity in our surround and keep on moving and hustling….(Cheers:-PN)

--

--