Recently, I worked on one of the Codility Training - Genomic Range Query (please refer to one of the evaluation report for the detail of the task.
The solution in Python is based on prefix sum, and was adjust in accordance to this article.
import copy
def solution(S, P, Q):
length_s = len(S)
length_q = len(Q)
char2digit_dict = {'A':1, 'C':2, 'G':3, 'T':4}
str2num = [0]*length_s
count_appearances = [[0, 0, 0, 0]]*(length_s+1)
cur_count = [0, 0, 0, 0]
for i in range(0, length_s):
str2num[i] = char2digit_dict[S[i]]
cur_count[str2num[i]-1] += 1
count_appearances[i+1] = copy.deepcopy(cur_count)
results = []
for i in range(0, length_q):
if Q[i] == P[i]:
results.append(str2num[Q[i]])
elif count_appearances[Q[i]+1][0] > count_appearances[P[i]][0]:
results.append(1)
elif count_appearances[Q[i]+1][1] > count_appearances[P[i]][1]:
results.append(2)
elif count_appearances[Q[i]+1][2] > count_appearances[P[i]][2]:
results.append(3)
elif count_appearances[Q[i]+1][3] > count_appearances[P[i]][3]:
results.append(4)
return results
However, the evaluation report said that it exceeds the time limit for large-scale testing case (the report link is above).
The detected time complexity is \$O(M * N)\$ instead of \$O(M + N)\$. But in my view, it should be \$O(M + N)\$ since I ran a loop for \$N\$ and \$M\$ independently (\$N\$ for calculating the prefix sum and \$M\$ for getting the answer).
Could anyone help me to figure out what the problem is for my solution? I get stuck for a long time. Any performance improvement trick or advice will be appreciated.