Last Updated: 8 Nov, 2020

Occurrence Of Each Word

Easy
Asked in companies
BarclaysIBMCoinbase

Problem statement

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.
Input format :
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.  
Constraints :
0 <= |S| <= 10^5 

Time Limit: 1sec

Approaches

01 Approach

Steps:

 

  • We iterate a given string, and while iterating the string, we maintain a temporary string word that stores the current word and then checks if we already count the word's occurrence previously by checking whether the word is present in the visited list.
  • If the word is not present, then insert it in the visited list, and count the occurrences of the word in the rest of the string.
  • Else, we simply skip that iteration.

02 Approach

A better solution is to use a Map that stores a unique word as a key and count its occurrence in a given string as a value.

 

Steps:

 

  • We iterate a given string and check whether the current word is already present in a map or not. If the current word is present, then increment the value of the current word in a map otherwise insert the current word as a key and 1 as a value in a map.
  • Then we iterate over the keys in the map and print the key-value pair as the output.