Home › Interview Questions › Write a Python program that reads a file where eac…

Write a Python program that reads a file where each line contains a single word and outputs the count of each word.

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

💡 Model Answer

A straightforward solution uses a dictionary to accumulate counts. Each line is stripped of whitespace and used as a key. The algorithm runs in linear time relative to the number of lines.

def word_count(file_path):
    counts = {}
    with open(file_path, 'r') as f:
        for line in f:
            word = line.strip()
            if word:
                counts[word] = counts.get(word, 0) + 1
    for word, count in sorted(counts.items()):
        print(f"{word}: {count}")

Complexity: Time O(n) where n is the number of lines; space O(k) where k is the number of unique words. The solution is efficient and easy to understand, making it suitable for a junior-level candidate.

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