Python Program to Find Most Frequent Word in String
collections.Counter to count words and most_common(1) to find the most frequent word like this: most_frequent = Counter(text.split()).most_common(1)[0][0].Examples
How to Think About It
Algorithm
Code
from collections import Counter def most_frequent_word(text): if not text: return "" words = text.split() count = Counter(words) return count.most_common(1)[0][0] # Example usage input_text = "apple banana apple orange banana apple" print(most_frequent_word(input_text))
Dry Run
Let's trace the input 'apple banana apple orange banana apple' through the code
Split the string
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
Count word frequencies
count = {'apple': 3, 'banana': 2, 'orange': 1}
Find most common word
most_common(1) returns [('apple', 3)]
Return the word
Return 'apple'
| Word | Count |
|---|---|
| apple | 3 |
| banana | 2 |
| orange | 1 |
Why This Works
Step 1: Splitting the string
We use split() to break the string into words so we can count each one separately.
Step 2: Counting words
The Counter creates a dictionary where keys are words and values are how many times they appear.
Step 3: Finding the most frequent word
The most_common(1) method returns the word with the highest count, which we then return.
Alternative Approaches
def most_frequent_word_manual(text): if not text: return "" words = text.split() freq = {} for word in words: freq[word] = freq.get(word, 0) + 1 max_word = max(freq, key=freq.get) return max_word print(most_frequent_word_manual("apple banana apple orange banana apple"))
from collections import defaultdict def most_frequent_word_defaultdict(text): if not text: return "" words = text.split() freq = defaultdict(int) for word in words: freq[word] += 1 max_word = max(freq, key=freq.get) return max_word print(most_frequent_word_defaultdict("apple banana apple orange banana apple"))
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string and counting words both take O(n) time where n is the number of words.
Space Complexity
We store counts for each unique word, which can be up to O(n) in the worst case.
Which Approach is Fastest?
Using collections.Counter is fastest and most readable; manual dictionary methods are slightly slower and more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| collections.Counter | O(n) | O(n) | Simplicity and speed |
| Manual dictionary | O(n) | O(n) | No imports, basic Python |
| defaultdict | O(n) | O(n) | Efficient counting without Counter |
collections.Counter for simple and efficient word frequency counting.