Liana
Liana

Reputation: 314

runtime error for python 3 code in a few test cases

I'm new to Python, and am trying to do this challenge: https://www.hackerrank.com/challenges/repeated-string/problem?h_r=internal-search I don't know why I get a runtime error when I submit my code. Here's my code:

s = input("Type a string: ")
n = int(input("Enter the number of repetition: "))
sf = ' '
repeat = n // len(s)
remain = n % len(s)
i = 0
j = 0 
if s == 'a':
    count = n
else:  
    while i < repeat:
        sf += s
        i += 1

    while j < remain:
        sf += s[j]
        j += 1

    count = sf.count('a')

print(count)

Any hints or solutions would be greatly appreciated!

NOTE: When you open the link it will ask you to sign up or log in. You can simply ignore it and it will then view the challenge.

Upvotes: 0

Views: 714

Answers (1)

zjb
zjb

Reputation: 400

The issue will come when the test sizes get really large. The string sf will get so large you will get a memory error. The challenging part of the problem is to figure out how to solve it without creating the long string.

Your approach with the remainder part is a good one. Maybe find how many 'a' s are in one sequence, then multiply it by the number of repeats? Then you just have to deal with the remainder part. You will need to figure out how many 'a' s are in the first 'remainder' characters of the string.

Upvotes: 2

Related Questions