Problem statement

https://leetcode.com/problems/most-common-word/

Solution

First of all, let us make all symbols small and remove all punctuation. Then we create set of banned words. Finally, we split our string and for each word if it is not banned, increase counter.

Complexity

Time complexity is O(n+m), where n is length of paragraph and m is length of all words in banned. Space complexity is O(m+n).

Code

class Solution:
    def mostCommonWord(self, paragraph, banned):
        paragraph = ''.join([c.lower() if c.isalpha() else ' ' for c in paragraph])
        words = paragraph.split()
        banned = set(banned)
        cnt = Counter()
        
        for word in words:
            if word not in banned:
                cnt[word] += 1
                
        return cnt.most_common(1)[0][0]