Instagram
youtube
Facebook

Word Order Hackerrank Optimized Solution

Mradul Mishra
Table of Contents

In this blog, we are going to find the most optimized solution for popular hacker rank question Word order. You are given n words. Some words may repeat. For each word, output its number of occurrences. The output order should correspond with the input order of appearance of the word. See the sample input/output for clarification. Note: Each input line ends with a "\n" character.

Steps Followed

  • In the first line of code we have imported counter from collections.
  • As the problem statement suggests we need to find the count of words. So for that, we have created a list of words.
  • In the next step we convert that list to a unique list using the counter module in python. 
  • Next in the step we printed the count of unique words in the list using len method.
  • Lastly we .values() method to find and print all the values of words inside res variable

Solution

# Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import Counter
n = int(input())
l1 = [input().strip() for _ in range(n)]
res = Counter(l1)
print(len(res))
print(*res.values())

 

Add a comment:

Comments:

Yash Jayesh Surve

A

subha vignesh

no comments

Jyoti Dwivedi

good