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.

Keep your next answer in view
MagicInterview Coach showing an example conversation beside its suggested answer
Illustrative product example · Add your own CV, role or meeting brief.
Live help with Pro

Bring your context. Get words to say live.

Pro recognizes the conversation and uses your CV, job description or meeting brief to suggest what to say in real time. Start listening once for automatic live suggestions. With the Mac app, follow the answers on a synced phone while you share your computer screen.

  1. 1. Choose Pro for live answersGet real-time suggestions during your interview or meeting.
  2. 2. Add your own contextCreate a free account to save your CV, job description or meeting brief.
  3. 3. Start listening during your callKeep suggested words in view while the conversation continues.
€49.99 for 48 hours of ProOne payment. No automatic renewal.

Create an account or sign in, then review the price before paying. Creating an account is free and does not charge you. Store plans have their own prices and renewal terms.

Try the free preparation preview

Explore all guides and tools