Most Common Word

Leetcode Problem 819

Mohit Kalra
1 min readJan 24, 2021

Given a paragraph, we have to ignore all the special characters and return the most frequent word which is not in the banned list of given words.

To start, we could have used a regular expression to get extract all the words from paragraph and ignore special characters, but regular expressions are not really intuitive to be asked in an interview. So, I chose to loop over each of the characters, ignore the special characters and just have the allowed characters pass through a filter.

I then run a collections.Counter over it to get the frequency. To sort the dictionary by frequency, I used the most_common() method provided by python.

There’s a weird test case due to which the problem got a lot of dislikes. I had to fix that by replacing the commas with spaces and adding spaces in the banned words because it ended up in my counter dictionary. But apart from that, the problem is very straightforward. The solution is pythonic, but it can be changed to a normal way of looping it through and then filtering.

References

--

--