I am trying to solve the below problem from an online coding site:
Fredo is pretty good at dealing large numbers. So, once his friend Zeus gave him an array of N numbers, followed by Q queries which he has to answer. In each query, he defines the type of the query and the number f for which Fredo has to answer. Each query is of the following two types:
- Type 0: For this query, Fredo has to answer the first number in the array (starting from index 0) such that its frequency is at least equal to f.
- Type 1: For this query, Fredo has to answer the first number in the array such that frequency is exactly equal to f.
Now, Fredo answers all his queries but now Zeus imagines how he should verify them. So, he asks you to write a code for the same.
Note: If there is no number which is the answer to the query, output 0. Use fast I/O.
Input:
- The first line of the input contains N, the size of the array
- The next line contains N space separated integers
- The next line contains Q, denoting the number of queries
Then follow Q lines, each line having two integers type and f, denoting the type of query and the frequency for which you have to answer the query.
Output:
You have to print the answer for each query in a separate line.
Input constraints:
- \$1 \le N \le 10^6\$
- \$1 \le A[i] \le 10^{18}\$
- \$1 \le Q \le 10^6\$
- \$0 \le \text{type} \le 1\$
- \$1 \le f \le 10^{18}\$
Sample input:
6 1 2 2 1 2 3 5 0 1 0 2 1 2 1 3 0 3
Sample output:
1 1 1 2 2
Here is the solution that I have tried:
from collections import Counter
import sys
tokenizedInput = sys.stdin.read().split()
t = int(tokenizedInput[0])
a = []
for i in range(t):
s = int(tokenizedInput[i+1])
a.append(s)
collection = Counter(a)
key = collection.keys()
value = collection.values()
q = int(tokenizedInput[i+2])
k = i+2
for j in range(q):
query = int(tokenizedInput[k+2*j+1])
f = int(tokenizedInput[k+2*j+2])
temp1 = list(key)
temp2 = list(value)
for w in range(t):
try:
index = temp1.index(a[w])
except:
continue
if query == 0:
if temp2[index] >= f:
print a[w]
break
else:
del temp1[index]
del temp2[index]
else:
if temp2[index] == f:
print a[w]
break
else:
del temp1[index]
del temp2[index]
if len(temp1) == 0:
print 0
break
if w == t-1:
print 0
This code runs properly and gives the correct output for smaller test cases but crosses the time limit on larger test cases. Can someone please suggest what improvements can be made to this code to improve the speed.