Rank Top Words
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace
Problem
Implement top_words(counts, limit). Return up to limit words ordered by descending count, breaking ties alphabetically.
Starter code
def top_words(counts, limit):
passTest cases
sample
{
"args": [
{
"beta": 2,
"alpha": 2,
"gamma": 1
},
2
]
}Expected: ["alpha","beta"]
Wizard outline
- Step 1: Encode frequency and tie ordering
Order every word by descending count and then alphabetically. A tuple key makes the primary and tie-break rules explicit in one deterministic ordering.
- Step 2: Return only the requested prefix
Return at most limit ranked words. Slicing naturally handles zero and limits larger than the number of words.
Footguns and prerequisites
- Alphabetical sorting alone ignores the primary frequency rank.
- functions
Reviewed references
Prepared Interview Problems
- Sort Characters by Frequency(opens in a new tab)
Ranking frequency entries by a deterministic compound key prepares the frequency-first ordering required when sorting characters.
- Top K Frequent Elements(opens in a new tab)
Selecting the first k entries after deterministic frequency ranking practices the candidate-ordering boundary in Top K Frequent Elements.
Recommended approach and implementation
Sort keys by a compound negative-count and word key.
Why it works: The key establishes descending frequency first and lexical order for every tie.
def _rank_words(counts):
return sorted(counts, key=lambda word: (-counts[word], word))
def top_words(counts, limit):
return _rank_words(counts)[:limit]