top-k-frequent-words.sh — zsh
hash-mapheapsortingstrings

Given an array of strings words and an integer k, return the k most frequent words.

The output order is part of the problem definition: you MUST rank words by frequency descending, and when two words have the same frequency, you MUST break ties by lexicographic (dictionary) ascending order. Use exact case-sensitive string comparison for that tie-break, so every correct solution returns the same deterministic array whether it uses sorting, a heap, or another approach.

Input / output

  • Input: words: string[], k: int
  • Output: string[]

Examples

  1. words = ["i","love","leetcode","i","love","coding"], k = 2 returns ["i","love"].
  2. words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4 returns ["the","is","sunny","day"].
  3. words = ["Apple","apple","Banana","banana","Apple","banana","Cherry","apple","banana","Cherry","Cherry"], k = 3 returns ["Cherry","banana","Apple"].

Constraints

  • 1 <= words.length <= 100000
  • 1 <= words[i].length <= 100
  • 1 <= k <= the number of distinct words in words
  • Words may repeat.
  • Comparisons are case-sensitive.

Follow-up If there are m distinct words, can you improve a full O(m log m) ranking into O(m log k) after counting frequencies by keeping only the current best k candidates in a heap?

Examples
Example 1
Input: words = ["i","love","leetcode","i","love","coding"], k = 2
Output: ["i","love"]
Example 2
Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4
Output: ["the","is","sunny","day"]