Count Word Frequency and Print Top Three Words
Company: PayPal
Role: Data Scientist
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates proficiency in basic Python programming, string/text processing, frequency counting and sorting algorithms, reflecting core competencies for data manipulation tasks.
Constraints
- Use only basic Python — no `collections.Counter`, no external libraries.
- Words are compared exactly as given (case-sensitive, no normalization).
- The list may be empty, in which case return an empty dict.
- If there are fewer than three unique words, print only the words that exist.
- The returned dictionary maps every unique word to its exact count.
Examples
Input: (["apple", "banana", "apple", "cherry", "banana", "apple"],)
Expected Output: {"apple": 3, "banana": 2, "cherry": 1}
Explanation: apple appears 3 times, banana 2, cherry 1. The dict captures all counts; the top-3 printed are apple, banana, cherry.
Input: (["a", "b", "c", "d"],)
Expected Output: {"a": 1, "b": 1, "c": 1, "d": 1}
Explanation: All four words are unique, each with frequency 1.
Input: ([],)
Expected Output: {}
Explanation: Empty input list returns an empty dictionary; nothing is printed.
Input: (["hello"],)
Expected Output: {"hello": 1}
Explanation: A single word appears once; only one word is available to print.
Input: (["x", "x", "x", "x"],)
Expected Output: {"x": 4}
Explanation: The same word repeated four times maps to a count of 4.
Input: (["red", "red", "blue", "green", "blue", "red", "yellow"],)
Expected Output: {"red": 3, "blue": 2, "green": 1, "yellow": 1}
Explanation: red=3, blue=2, then green and yellow tie at 1; the top-3 printed are red, blue, and one of the singletons.
Hints
- Initialize an empty dict and loop over the words: if the word is already a key, increment its value; otherwise set it to 1.
- Use `sorted(freq.items(), key=lambda kv: kv[1], reverse=True)` to order the words by frequency from highest to lowest.
- Slice the sorted list with `[:3]` to take only the top three, then print each `word count` pair.