HomeInterview QuestionsCount how many times each word appears and show th…

Count how many times each word appears and show the result in a dictionary.

🟡 Medium Coding Junior level
1Times asked
Jun 2026Last seen
Jun 2026First seen

💡 Model Answer

To count word frequencies, split the input text into words, normalize them (e.g., lower‑case, strip punctuation), and iterate through the list, updating a dictionary where keys are words and values are counts. In Python, this can be done with a simple for‑loop or using collections.Counter. The algorithm runs in O(n) time, where n is the number of words, and uses O(k) additional space for k unique words. Example:

python
import re
from collections import Counter

def word_count(text):
    words = re.findall(r"\b\w+\b", text.lower())
    return Counter(words)

text = "Hello world! Hello again."
print(word_count(text))  # Counter({'hello': 2, 'world': 1, 'again': 1})

This approach handles large inputs efficiently and can be extended to ignore stop words or perform case‑insensitive matching as needed.

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 — invisible to screen sharing.

Get Assisting AI — Starts at ₹500