You are given a string S of words. Your task is to count the occurrence of each word present in the string S. A word is a sequence of one or more non-space characters, and there can be multiple spaces between two words, and also there can be leading or trailing spaces in a string S.
For Example:For the given string “what we think we become”
“what”,” think”, and “become” occurs 1 time, and “we” occurs 2 times in the given string.
The first and the only line of input contains a string S.
Output format :
For each unique word in the given string, print the word along with its count of occurrence separated by a space in the new line.
Note:
You can print the output in any order.
0 <= |S| <= 10^5
Time Limit: 1sec
learning to learn
learn 1
learning 1
to 1
For the given string, “learning”, “to”, and “learn” occurs only 1 time.
what we think we become
think 1
what 1
we 2
become 1
Think of brute force by checking for each unique word and count its occurrence in the rest of the string.
Steps:
O(N * (M+N)), where N is the length, and M is the number of unique words in the given string.
In the worst case, for each word in the string (O(N)), we will check if a current word is present in the visited list that takes O(M), and count the occurrence of a current word in the rest of the string (O(N)).
Hence the overall complexity will be O(N * (M+N) time.
O(M), where M is the number of unique words in the given string.
In the worst case, we will be storing all unique words present in the string in the visited list.