I need help.
The link above is the question on hackerrank. I have solved the problem and I was allowed to do the next challenge but I don't think my solution is the most optimized. I really wanna know about the best possible approach.
My code / solution:
def matchingStrings(strings, queries):
# Write your code here
# strings = sorted(strings)
# queries = sorted(queries)
results = []
LENGTH_Q = len(queries)
LENGTH_S = len(strings)
for i in range(LENGTH_Q):
total = 0
query = queries[i]
for j in range(LENGTH_S):
string = strings[j]
if query == string:
total += 1
results.append(total)
return results
I believe my solution results to quadratic complexity which is not good. Please show me or give me hints on how to think of a better solution to this problem.
Thank you.
UPDATE:
I have a second version of my solution but still not sure if it is more efficient because I don't know how the function [LIST].count()
works inside. Anyway, please take a look the 2nd version:
def matchingStrings2(strings, queries):
results = []
LENGTH_Q = len(queries)
for i in range(LENGTH_Q):
query = queries[i]
results.append(strings.count(query))
return results