• + 0 comments

    Counter from collections module provides for us O(n) here:

    import sys
    from collections import Counter
    
    input = sys.stdin.read().splitlines()
    n = int(input[0])  
    words = input[1:]  
    
    counter = Counter(words)
    distinct_words = list(dict.fromkeys(words))  
    
    print(len(distinct_words))
    print(" ".join(str(counter[word]) for word in distinct_words))