Search code examples
pythonpython-3.xlisttimeoutdeque

Why do I still get "Terminated due to timeout error" even after using deque instead of list?


I have written the following code to output the number of distinct words from the input and also their number of occurrences for each distinct word according to their appearance in the input.

I used the list append and count method and got the desired output, but some of the test cases didn't execute due to timeout error.

n = int(input())
ar = []
for _ in range(n):
    ar.append(input().rstrip())

def wordOrder(n, ar):    
    w_list =[] #list contains the number of repition of words
    u_list =[] #list eliminates the duplicates while maintaining the same order
    for i in ar:
        if i not in u_list:
            u_list.append(i)
            w_list.append(ar.count(i))
       
    return w_list
    
result = wordOrder(n, ar)
print(len(result))
print(*result, sep=' ')

So, I tried using deque instead of list thinking it might be due to the time complexity issue of O(n) for the list append method. But I am getting the same error even after using deque.

My question is whether the problem is due to the time complexity issue or some other factors? Would be great if someone could explain what kind of techniques to be adapted to avoid timeout error.

Sample Input:

4
bcdef
abcdefg
bcde
bcdef

Sample Output:

3
2 1 1

Solution

  • This code works fine for me

    from collections import Counter
    
    a=[]
    
    for i in range(int(input())):
    
          a.append(input())
    
    x = Counter(a)
    
    print(len(x.keys()))
    
    print(*x.values())