KatInterview

692. Top K Frequent Words

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to find the k most frequent words from a given list. The result must be sorted in a specific way: primarily by frequency in descending order, and secondarily by lexicographical order (alphabetical order) in ascending order for words with the same frequency.

Solution

Top K Frequent Words in Python

import collections
import heapq

# Wrapper class to define custom comparison for the min-heap.
# Python's heapq doesn't directly support custom key functions like sorted().
class Element:
    def __init__(self, word, freq):
        self.word = word
        self.freq = freq

    # __lt__ is used for comparison in the min-heap.
    def __lt__(self, other):
        # If frequencies are the same, the one with the larger lexicographical
        # value is considered "smaller" so it gets popped from the min-heap first.
        if self.freq == other.freq:
            return self.word > other.word
        # Otherwise, the one with the smaller frequency is considered "smaller".
        return self.freq < other.freq

class Solution:
    def topKFrequent(self, words: List[str], k: int) -> List[str]:
        # Step 1: Count word frequencies
        counts = collections.Counter(words)

        # Step 2: Use a min-heap to find top k elements
        min_heap = []
        for word, freq in counts.items():
            # Push the custom element wrapper to the heap
            heapq.heappush(min_heap, Element(word, freq))
            # If heap size exceeds k, pop the smallest element
            if len(min_heap) > k:
                heapq.heappop(min_heap)

        # Step 3: Extract words from the heap and format the result
        result = []
        while min_heap:
            # Pop from heap and get the word
            result.append(heapq.heappop(min_heap).word)
        
        # The elements are popped in increasing order of "smallness".
        # This means lowest frequency first, or highest lexicographical for ties.
        # We need to reverse to get the desired final order.
        return result[::-1]

Top K Frequent Words in Java

class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        // Step 1: Count word frequencies
        Map<String, Integer> freqMap = new HashMap<>();
        for (String word : words) {
            freqMap.put(word, freqMap.getOrDefault(word, 0) + 1);
        }

        // Step 2: Use a min-heap (PriorityQueue) to find top k elements
        // The comparator sorts by frequency ascending. If frequencies are equal,
        // it sorts by word descending (lexicographically).
        // This ensures the element to be kicked out (the "smallest") is at the top.
        PriorityQueue<String> minHeap = new PriorityQueue<>(
            (word1, word2) -> {
                int freq1 = freqMap.get(word1);
                int freq2 = freqMap.get(word2);
                if (freq1 != freq2) {
                    return freq1 - freq2; // Sort by frequency ascending
                } else {
                    return word2.compareTo(word1); // Sort by word descending
                }
            }
        );

        for (String word : freqMap.keySet()) {
            minHeap.offer(word);
            if (minHeap.size() > k) {
                minHeap.poll();
            }
        }

        // Step 3: Extract words from the heap and format the result
        List<String> result = new ArrayList<>();
        while (!minHeap.isEmpty()) {
            result.add(minHeap.poll());
        }

        // The heap gives elements in increasing order of frequency.
        // We need to reverse to get decreasing order.
        Collections.reverse(result);

        return result;
    }
}

Top K Frequent Words in C++

class Solution {
public:
    vector<string> topKFrequent(vector<string>& words, int k) {
        // Step 1: Count word frequencies
        unordered_map<string, int> freq_map;
        for (const string& word : words) {
            freq_map[word]++;
        }

        // Define a type for heap elements for clarity
        using FreqPair = pair<int, string>;

        // Step 2: Use a min-heap to find top k elements
        // The custom comparator for the min-heap.
        // It orders pairs such that the one with lower frequency is "smaller".
        // If frequencies are equal, the one with higher lexicographical order is "smaller".
        auto comp = [](const FreqPair& a, const FreqPair& b) {
            if (a.first != b.first) {
                return a.first > b.first; // Min-heap based on frequency
            }
            return a.second < b.second; // Max-heap based on word for ties
        };
        
        // C++ priority_queue is a max-heap by default. To make it a min-heap,
        // we provide a comparator that returns true if the first arg is "greater" than the second.
        priority_queue<FreqPair, vector<FreqPair>, decltype(comp)> min_heap(comp);

        for (auto const& [word, freq] : freq_map) {
            min_heap.push({freq, word});
            if (min_heap.size() > k) {
                min_heap.pop(); // Remove the element with lowest frequency (or highest lexicographically)
            }
        }

        // Step 3: Extract words from the heap and format the result
        vector<string> result;
        while (!min_heap.empty()) {
            result.push_back(min_heap.top().second);
            min_heap.pop();
        }

        // The heap gives elements in increasing order of frequency.
        // We need to reverse to get decreasing order.
        reverse(result.begin(), result.end());

        return result;
    }
};

Top K Frequent Words in TypeScript

function topKFrequent(words: string[], k: number): string[] {
    // Type definition for elements to be stored in the heap.
    type FreqPair = { word: string; freq: number };

    // Min-Heap implementation using a class.
    class PriorityQueue<T> {
        private heap: T[] = [];
        private compare: (a: T, b: T) => number;

        constructor(compareFn: (a: T, b: T) => number) {
            // The comparator function should return a negative value if a < b,
            // zero if a == b, and a positive value if a > b.
            this.compare = compareFn;
        }

        size(): number { return this.heap.length; }
        peek(): T | undefined { return this.heap[0]; }

        push(val: T): void {
            this.heap.push(val);
            this.siftUp(this.heap.length - 1);
        }

        pop(): T | undefined {
            if (this.size() <= 1) return this.heap.pop();
            const popped = this.heap[0];
            this.heap[0] = this.heap.pop()!;
            this.siftDown(0);
            return popped;
        }

        private getParentIndex(i: number): number { return Math.floor((i - 1) / 2); }
        private getLeftChildIndex(i: number): number { return 2 * i + 1; }
        private getRightChildIndex(i: number): number { return 2 * i + 2; }

        private siftUp(i: number): void {
            let p = this.getParentIndex(i);
            while (i > 0 && this.compare(this.heap[i], this.heap[p]) < 0) {
                [this.heap[i], this.heap[p]] = [this.heap[p], this.heap[i]];
                i = p;
                p = this.getParentIndex(i);
            }
        }

        private siftDown(i: number): void {
            let smallest = i;
            const left = this.getLeftChildIndex(i);
            const right = this.getRightChildIndex(i);
            const size = this.size();

            if (left < size && this.compare(this.heap[left], this.heap[smallest]) < 0) {
                smallest = left;
            }
            if (right < size && this.compare(this.heap[right], this.heap[smallest]) < 0) {
                smallest = right;
            }
            if (smallest !== i) {
                [this.heap[i], this.heap[smallest]] = [this.heap[smallest], this.heap[i]];
                this.siftDown(smallest);
            }
        }
    }

    // Step 1: Count word frequencies
    const freqMap = new Map<string, number>();
    for (const word of words) {
        freqMap.set(word, (freqMap.get(word) || 0) + 1);
    }

    // Step 2: Use a min-heap to find top k elements
    // Comparator for the min-heap: sorts by frequency ascending.
    // If frequencies are equal, sorts by word descending (lexicographically).
    const comparator = (a: FreqPair, b: FreqPair): number => {
        if (a.freq !== b.freq) {
            return a.freq - b.freq;
        }
        return b.word.localeCompare(a.word); // a is smaller if b's word comes first
    };

    const minHeap = new PriorityQueue<FreqPair>(comparator);

    for (const [word, freq] of freqMap.entries()) {
        minHeap.push({ word, freq });
        if (minHeap.size() > k) {
            minHeap.pop();
        }
    }

    // Step 3: Extract words from the heap and format the result
    const result: string[] = [];
    while (minHeap.size() > 0) {
        result.push(minHeap.pop()!.word);
    }

    // Reverse to get the final sorted order
    return result.reverse();
}

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.