Home β€Ί Interview Questions β€Ί Write Python logic to count word frequency in a st…

Write Python logic to count word frequency in a string.

🟑 Medium Coding Junior level
1Times asked
Jul 2026Last seen
Jul 2026First seen

πŸ’‘ Model Answer

You can solve this by splitting the string into words and using a dictionary or collections.Counter to tally occurrences. For example:

python
from collections import Counter

def word_frequency(text):
    # Normalize: lower case and split on whitespace
    words = text.lower().split()
    return Counter(words)

text = "Hello world hello"
print(word_frequency(text))  # Counter({'hello': 2, 'world': 1})

This runs in O(n) time where n is the number of words, and uses O(k) space for k unique words. If you need to handle punctuation, use regex or str.translate to strip punctuation before splitting.

This answer was generated by AI for study purposes. Use it as a starting point β€” personalize it with your own experience.

🎀 Get questions like this answered in real-time

Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.

Get Assisting AI β€” Starts at β‚Ή500