Question: http://qa.geeksforgeeks.org/9744/vinay-queried-interesting-problem-optimization
Input
The first line contains N denoting the length of Target String. This line is followed by the Target String. The Target String is followed by an integer Q denoting the number of queries asked. After this Q lines follow each line containing a Query String.
Output
For each query output the total number of distinct Cruel Pairs that satisfies the given conditions.
Constraints
1 ≤ N ≤ 5000
1 ≤ Q ≤ 104
Sum of Lengths of all Query Strings ≤ 106
All strings are composed only of '0' - '9'Sample Input
5 75201 5 78945884875 22 00048 77 501
Sample Output
0 8 8 6 5
Explanation
Query String 1 : No such Pair exist.
Query String 2 : Pairs are (1,2) , (1,3) , (1,4) , (1,5) , (2,3) , (2,4) , (2,5) , (3,5)
Query String 5 : Pairs are (1,3) , (1,4) , (1,5) , (2,4) , (2,5)
Time Limit:1.0 sec(s) for each input file. 5s for python
Memory Limit:256 MB
Source Limit:1024 KB
Please review the code and help me with optimization
N = int(raw_input())
target = str(int(raw_input()))
N = len(target)
Q_N = int(raw_input())
queries_list = []
output = []
for x in xrange(Q_N):
queries_list.append(raw_input())
for x in queries_list:
d = int(str(int(x))[0])
x = str(int(x))
q_l = len(x)
if q_l > N:
print 0
continue
count = 0
for i, t in enumerate(target):
t = int(t)
temp = 0
if t > d:
temp = (N - i) - q_l + 1
elif t > 0 and t < d:
temp = (N - i) - q_l
elif t == d:
temp = (N - i) - q_l
if int(target[i:i + q_l]) > int(x):
temp = temp + 1
if temp > 0:
count = count + temp
print count