Tuesday, June 20, 2017

Hackerrank Solution: Repeated String

Problem Link

Solution Link

Explanation:

This is a simple string manipulation problem. At first we count the number of a's in the given string and the number is saved in countA variable. We just subtract the number of non- a characters from the string length to find that out. Since we are taking a n-length part from an infinite-repeating string, the n-long part will have several occurrences of string s. The variable chunk determines the number of occurrence. So chunk*countA represents number of a's in chunk number of s strings. We may have a remainder string portion for which we used a separate for loop count the number of a's there. Last we print out the result.
Runtime: O(n) We used a single loop.

Note: Here n is long type variable because of the constraint 1<=n<=10^12. In Java integer range is -2,147,483,648 to 2,147,483, 647    .And  the range for long is -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

so we have chosen a long type variable for n.

You can learn more about Java's variable type ranges here.



No comments:

Post a Comment

CodeForces: Xenia and Ringroad(339B) Solution in Java for Beginners

  Xenia and Ringroad(339B) Problem Link: Since this is a beginner's problem, I suggest you try it out yourself first. Java programm...