Top K Frequent Words solution explained

Top K Frequent Words asks for the k most common words in a list, ordered from most to least frequent, with ties broken alphabetically. Count the words with a hash map, then either sort the distinct words by the key (negative count, word) and take the first k, or keep a heap of size k whose root is the weakest kept word: the lowest count, and among equal counts the alphabetically latest. Sorting costs O(u log u) for u distinct words; the heap costs O(u log k).

By Published 8 min read

The problem, restated

You get a list of lowercase words and a number k that is at least 1 and at most the number of distinct words. Return the k words that appear most often. Order the result by count from high to low, and when two words have the same count, put the one that comes first in dictionary order first.

Examples written for this page
WordskOutputWhy
[pear, fig, pear, kiwi, fig, pear, date]2[pear, fig]Counts 3 and 2
[pear, fig, pear, kiwi, fig, pear, date]3[pear, fig, date]date and kiwi tie at 1; date comes first alphabetically
[b, a, c, b, a, c]2[a, b]All tie at 2, so the first two alphabetically
[sun]1[sun]One word
Examples written for this page. Scroll sideways on a small screen.

Compared with Top K Frequent Elements, the counting is identical. What changes is that the output order is fully specified, ties included, so any approach must respect a two-part ordering in which one part is descending and the other ascending.

What the interviewer is testing

Interviewers use this problem to check comparator thinking. Almost everyone counts correctly. Fewer people get the heap right, because a min-heap of size k must evict the weakest word, and the weakest word among equal counts is the alphabetically latest one, not the earliest. Candidates who reach for a tuple heap of (count, word) get the tie-break backwards and only find out on a tie-heavy test. Being able to explain why the comparator flips is the signal.

Follow-ups

  • The words arrive as a stream. Keep counts in a map; answering a query needs a heap pass over the map, or a balanced ordered structure updated on each word.
  • Case-insensitive counting. Normalize case before counting, and decide which original spelling to report.
  • Huge input that does not fit in memory. Count in chunks, merge partial counts by hashing words to files, then select per file.
  • Least frequent words instead. Flip the count direction but keep the alphabetical tie-break.

Count, then sort everything

This is the version to write first, because it is short and hard to get wrong. Sorting by the key (negative count, word) puts higher counts first and, among equal counts, alphabetical order. In an interview where u is modest, it is a perfectly good final answer; say so, and offer the heap as the improvement when k is much smaller than u.

from collections import Counter

def top_k_words_sorted(words, k):
    counts = Counter(words)
    ranked = sorted(counts, key=lambda w: (-counts[w], w))
    return ranked[:k]
Python: one sort with a two-part key.
function topKWordsSorted(words, k) {
  const counts = new Map();
  for (const w of words) counts.set(w, (counts.get(w) || 0) + 1);
  const ranked = Array.from(counts.keys()).sort((a, b) => {
    const diff = counts.get(b) - counts.get(a);
    if (diff !== 0) return diff;
    return a < b ? -1 : a > b ? 1 : 0;
  });
  return ranked.slice(0, k);
}
JavaScript: a comparator that handles both parts.

The tie-break compares strings with < and >, which follows character codes. That matches the usual "lexicographical order" for lowercase words. localeCompare would also work for plain lowercase input, but it applies language rules that can differ from code-point order for accents or mixed case, so avoid it unless asked.

A heap that keeps only k words

When k is small, sorting every distinct word is wasted work. Keep a min-heap of at most k entries whose root is the weakest word kept so far. Push each word; if the heap grows past k, pop the root. At the end, the heap holds the top k, and popping it gives them weakest first, so reverse.

What "weaker" means in the heap
SituationWeaker word (closer to the root)
Different countsThe one with the lower count
Same countThe one later in alphabetical order
What "weaker" means in the heap. Scroll sideways on a small screen.
import heapq
from collections import Counter

class Entry:
    def __init__(self, count, word):
        self.count = count
        self.word = word

    def __lt__(self, other):  # True when self is weaker than other
        if self.count != other.count:
            return self.count < other.count
        return self.word > other.word

def top_k_words_heap(words, k):
    heap = []
    for word, count in Counter(words).items():
        heapq.heappush(heap, Entry(count, word))
        if len(heap) > k:
            heapq.heappop(heap)
    result = []
    while heap:
        result.append(heapq.heappop(heap).word)
    return result[::-1]
Python: a size-k heap with a custom ordering.

In Python, heapq.nsmallest(k, counts, key=lambda w: (-counts[w], w)) does the same selection with a bounded heap internally and returns the words in final order. It is a fine thing to mention, but interviewers often ask for the explicit version to see the comparator.

function topKWordsHeap(words, k) {
  const counts = new Map();
  for (const w of words) counts.set(w, (counts.get(w) || 0) + 1);

  const weaker = (a, b) =>
    a.count !== b.count ? a.count < b.count : a.word > b.word;
  const heap = [];
  const swap = (i, j) => { [heap[i], heap[j]] = [heap[j], heap[i]]; };
  const push = (item) => {
    heap.push(item);
    let i = heap.length - 1;
    while (i > 0) {
      const parent = (i - 1) >> 1;
      if (!weaker(heap[i], heap[parent])) break;
      swap(i, parent);
      i = parent;
    }
  };
  const pop = () => {
    const root = heap[0];
    const last = heap.pop();
    if (heap.length > 0) {
      heap[0] = last;
      let i = 0;
      for (;;) {
        const l = 2 * i + 1;
        const r = l + 1;
        let m = i;
        if (l < heap.length && weaker(heap[l], heap[m])) m = l;
        if (r < heap.length && weaker(heap[r], heap[m])) m = r;
        if (m === i) break;
        swap(i, m);
        i = m;
      }
    }
    return root;
  };

  for (const [word, count] of counts) {
    push({ word, count });
    if (heap.length > k) pop();
  }
  const result = [];
  while (heap.length > 0) result.push(pop().word);
  return result.reverse();
}
JavaScript: a small binary heap with the same "weaker" rule.

Trace the second example with k = 3. Counts: pear 3, fig 2, kiwi 1, date 1. After pear, fig and kiwi the heap is full with kiwi at the root. Pushing date makes four entries; date and kiwi tie at 1, and kiwi is later alphabetically, so kiwi is weaker and gets popped. Popping the rest gives date, fig, pear, and reversing yields [pear, fig, date].

Bucket variant

Counts are at most n, so you can group words into buckets by count, walk the buckets from high to low and sort the words inside each bucket alphabetically. That avoids comparing counts at all, but the alphabetical sort inside a big bucket still costs a log factor, so it is not strictly better than the heap in the worst case.

Complexity

n words in total, u distinct, string comparisons counted as O(1)
ApproachTimeExtra memory
Count, then sort all distinct wordsO(n + u log u)O(u)
Count, then a size-k heapO(n + u log k)O(u) for counts, O(k) for the heap
Count, then buckets sorted alphabeticallyO(n + u log u) in the worst caseO(n + u)
n words in total, u distinct, string comparisons counted as O(1). Scroll sideways on a small screen.

Comparing two words really costs time proportional to their length. Interviewers rarely expect that in the formula, but mentioning it shows care.

Edge cases

  • k equal to the number of distinct words: return all of them in full order.
  • All words distinct: every count is 1, so the answer is the first k words alphabetically.
  • All words the same: one distinct word, k must be 1.
  • Words that are prefixes of each other, such as "art" and "arts"; the shorter one sorts first.
  • Mixed case, if allowed: uppercase letters sort before lowercase by code point.

Common mistakes

  • Pushing (count, word) tuples into a min-heap, which evicts the alphabetically earliest word on a tie, the opposite of what is needed.
  • Forgetting to reverse after popping the heap.
  • Sorting by count descending and word descending in one reversed sort.
  • Using localeCompare in JavaScript and getting a different order for unusual characters.
  • Returning words in heap array order, which is not sorted.

How to explain it out loud

Fictional example

Getting the comparator right
Candidate
Counting is a hash map pass. The interesting part is the order: higher count first, and alphabetical among ties. Sorting with the key negative count, then word, does both in one line.
Candidate
If k is much smaller than the number of distinct words, I will keep a min-heap of size k. The root has to be the word I would drop first, which is the lowest count, and on a tie the one later in the alphabet. That is the flip people miss.
Candidate
At the end I pop everything and reverse. Sorting costs u log u, the heap u log k, both after a linear count.

Top K Frequent Elements is the same task on numbers, where ties need no ordering and bucketing gives linear time. Reorganize String and Maximum Frequency Stack are two more problems driven by counts, one placing the most frequent item first and the other removing it. Kth Missing Positive Number is a lighter warm-up on counting in order.

Practicing with Natively

Comparator bugs hide until a tie appears, so build tie-heavy test cases into your practice. In a practice session on Mac or Windows, Natively can read the problem statement from a screenshot and suggest an approach to set beside yours after you have tried, and the transcript of your mock round shows whether you explained the flipped tie-break or skipped it. Read about the AI interview assistant.

Questions people ask

How do you solve Top K Frequent Words?

Count words with a hash map, then sort the distinct words by negative count and then alphabetically and take the first k, or keep a min-heap of size k and reverse it at the end.

How should the heap compare words with the same count?

In a size-k min-heap, the word later in alphabetical order must count as weaker, so it is evicted first. A plain (count, word) tuple gets this backwards.

What is the time complexity of Top K Frequent Words?

O(n + u log u) with sorting and O(n + u log k) with a size-k heap, for n words and u distinct words.

How is this different from Top K Frequent Elements?

The counting is the same, but here the output order is fully defined, with ties broken alphabetically, so the comparator matters.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP