Skip to main content
Back to problems
#692
Medium Algorithms

Top k frequent words

Array Hash Table String Trie Sorting Heap (Priority Queue) Bucket Sort Counting
60.0% acceptance
Feb 20, 2026
8008
374
Given an array of strings words and an integer k, return the k most frequent strings sorted by frequency (desc) and lexicographically (asc) for ties.

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
use std::collections::HashMap;
impl Solution {
  pub fn top_k_frequent(words: Vec<String>, k: i32) -> Vec<String> {
    let mut freq: HashMap<String, i32> = HashMap::new();
    for w in words {
      *freq.entry(w).or_insert(0) += 1;
    }
    let mut pairs: Vec<(String, i32)> = freq.into_iter().collect();
    pairs.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
    pairs.into_iter().take(k as usize).map(|(w, _)| w).collect()
  }
}