Medium: Interview Core · Problem 38 of 82

Most Common, Ties Broken

MediumDictionaries and SetsPython

Write most_common(words, k) that returns a list of (word, count) tuples for the k words that appear most often, highest count first. Words with the same count are ordered alphabetically. If there are fewer than k different words, return them all.

Understand the problem

Look at how ties are ordered by default.

Counter(["b", "a", "b", "a", "c"]).most_common(2) gives [("b", 2), ("a", 2)]. Why is b before a?

  1. Because b is alphabetically first
  2. Because b was seen first: ties keep the order of first appearance
  3. Because of a random choice

most_common sorts by count, and for equal counts it keeps the order in which the words first appeared (the dictionary order). It does not sort alphabetically. If the task asks for alphabetical ties, you must do it yourself.

sorted(counts.items(), key=lambda p: (-p[1], p[0])). What order does this give?

  1. Count ascending, then word ascending
  2. Count descending, then word ascending
  3. Word first, then count

The key is a tuple. -p[1] puts the highest count first, and p[0] (the word) breaks ties alphabetically. This is the standard trick for "descending by one thing, ascending by another".

Write the solution

Return the top k pairs.

def most_common(words, k):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

First count the words. Then what sort order do you need?

Hint 2: the shape of the answer

Count with Counter (or a dictionary), sort the (word, count) pairs with the key above, and slice the first k.

Reflect

Solution

from collections import Counter

def most_common(words, k):
    counts = Counter(words)
    ordered = sorted(counts.items(), key=lambda pair: (-pair[1], pair[0]))
    return ordered[:k]

Another way: heapq.nsmallest with the same key

import heapq
from collections import Counter

def most_common(words, k):
    counts = Counter(words)
    return heapq.nsmallest(k, counts.items(), key=lambda pair: (-pair[1], pair[0]))

What this tests: Counter, sorting with a composite key, slicing, and reading what a library function actually promises.

Don't trust a default order for ties. most_common is correct for "top k", but its tie order is an implementation detail of first appearance. When the task states a tie-break, write it into the sort key.

nsmallest with the key finds the top k without sorting everything, O(n log k). With a small k and a long list it is faster; with a small list it does not matter.

Cost: O(n + u log u) for u distinct words with the full sort.

What an interviewer might ask next: Do it for a stream of a billion words where you cannot keep all the counts in memory. (Approximate with a Count-Min sketch or a Space-Saving counter.)