Answer the question
In order to leave comments, you need to log in
Why is the second code faster?
The input is a string s and t, numbers l,r. The essence of the problem is to find the number of occurrences of the string t in a substring of s, where l and r are the numbers of explicit boundaries of the string s. That is, l = 1, r = 3, s = '12345', the searched substring will be '123'. The number m is the length s.
The first version of the code does not pass in time. Why? As I see it, the number of operations in the first option is no more than in the second one, but count() is much faster than a loop with comparisons. Is it so? Which operations are difficult and which are easy in both options?
n, m, q = [int(i) for i in input().split()]
s = input()
t = input()
for i in range(q):
l,r = map(int, input().split())
count = 0
if r - l + 1 >= m:
for j in range(l-1, r - m + 1):
if s[j:j + m] == t:
count += 1
print(count)
n, m, q = [int(i) for i in input().split()]
s = input()
t = input()
positions = ''
for i in range(n-m+1):
if s[i:i + m] == t:
positions += '1'
else:
positions += '0'
for i in range(q):
l,r = map(int, input().split())
if r - l + 1 >= m:
print (positions[l-1:r-m+1].count('1'))
else:
print(0)
Answer the question
In order to leave comments, you need to log in
At a cursory glance, due to the different complexity of the algorithm. See, in the first loop in the loop - it looks like there's quadratic complexity. The second is linear. Google for these terms.
https://en.wikipedia.org/wiki/%D0%92%D1%8B%D1%87%D...
Which operations are difficult and which are easy in both options?Of course, determining such operations "by eye" is a very cool skill, but it is quite difficult to pump it.
I suggest that you familiarize yourself with my solution to this problem ( https://codeforces.com/contest/1016/problem/B) at the link: https://codeforces.com/contest/1016/submission/41169503
The solution turned out to be the fastest among other solutions on third Python, you can check it here: https://codeforces.com/contest/1016/status/B/page/... (you need to select the Python 3 language in the status filter)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question