You have been given two strings, A and B (of length N each) and Q queries. The strings contain only 0s and/or 1s.
For every query, you are given an index i. You have to update the value at index i to 1 in string B and check if B is lexicographically equal to or larger than A or not. If yes, then print "YES" and if not, print "NO" (without quotes).
Input format
First line contains two space-separated integers N and Q. Next line contains the string A. Next line contains the string B. Next Q lines contains an integer i (1 - based indexing)
Output Format
For each query, print the desired output in a new line.
Sample Input
5 5 11111 00010 1 2 3 4 5
Sample Output
NO NO NO NO YES
Explanation
After 1st query: B = 10010. B < A. (NO) After 2nd query: B = 11010. B < A. (NO) After 3rd query: B = 11110. B < A. (NO) After 4th query: B = 11110. B < A. (NO) After 5th query: B = 11111. B = A. (YES)
My solution in Python:
# Write your code here
N_Q = list(map(int, input().split()))
string_a_list = list(input())
string_b_list = list(input())
different_set = set()
for index in range(N_Q[0]):
if string_a_list[index] != string_b_list[index]:
different_set.add(index + 1)
for query in range(N_Q[1]):
index_q = int(input()) # 1 based
index = index_q - 1
string_b_list[index] = 1
if len(different_set) == 0:
break
if int(string_a_list[index]) == int(string_b_list[index]):
different_set.discard(index_q)
if len(different_set) != 0:
print("NO")
if len(different_set) == 0:
print("YES")
if len(different_set) > 0:
firstIndex = next(iter(different_set))
index == firstIndex - 1
if int(string_a_list[index]) > int(string_b_list[index]):
print("NO")
if int(string_a_list[index]) < int(string_b_list[index]):
print("YES")
But for one test case that has got really very large input it's taking 5 sec so I'm getting timeout for that case:
Input #8 5.001169 22512 0
How can I optimize this further? What are the critical points to solve problem like this that I'm missing?