#692

Top K Frequent Words

Medium Heap with a two-key comparator

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the k most frequent words, sorted by frequency (high to low) and alphabetically for ties.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the k most frequent words, ties in alphabetical order.

Why this works: a min-heap of size k where the "worst" word sits on top (lower count, or later alphabetically). Reverse at the end.

Example: ["i","love","leetcode","i","love","coding"], k = 2

i:2, love:2, others 1tie → "i" before "love" → ["i", "love"]

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Getting the tie-break backwards inside the min-heap — it must be the reverse of the final order.

Solve on LeetCode ↗
Complexity
  • Time: O(n log k).
  • Space: O(n).
Topic: Heaps & Priority Queue
🎬 Episodes 64–68: video coming soon