Guide

Explain frequency sorting and tie-breaking

An original Python coding rehearsal with frequency sorting, tie-breaking, edge cases and complexity.

By MagicInterviewLast updated

This original exercise asks for the most frequent words, breaking equal frequencies alphabetically. It is a rehearsal task, not a claim about a company's actual question bank.

State the contract#

Assume a list of strings and a nonnegative integer k. Return at most k words. For an empty list or k equal to zero, return an empty list. Decide whether case is significant before coding; the example below treats different cases as different strings.

from collections import Counter

def top_k_words(words, k):
    if k < 0:
        raise ValueError("k must be nonnegative")
    counts = Counter(words)
    return sorted(counts, key=lambda word: (-counts[word], word))[:k]

Explain the trade-off#

Count occurrences, then sort distinct words by descending count and ascending word. With n inputs and u distinct words, counting takes O(n), sorting takes O(u log u) comparisons, and storage is O(u); string comparison cost also depends on word length. This straightforward version sorts all distinct words even when k is small.

Test repeated words, equal counts, k larger than u and empty input. For ["b", "a", "b", "a", "c"] with k equal to two, the result is ["a", "b"]. Practise explaining why the minus sign reverses the count order. Use the technical story guide to connect coding choices to reasoning, and prepare a rehearsal from your own work.

Explore all guides and tools