Solving Leetcode Interviews in Seconds with AI: Top K Frequent Words
Introduction
In this blog post, we will explore how to solve the LeetCode problem "692" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
Problem Statement
Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by the frequency from highest to lowest. Sort the words with the same frequency by their lexicographical order. Example 1: Input: words = ["i","love","leetcode","i","love","coding"], k = 2 Output: ["i","love"] Explanation: "i" and "love" are the two most frequent words. Note that "i" comes before "love" due to a lower alphabetical order. Example 2: Input: words = ["the","day","is","sunny","the","the","the","sunny","is","is"], k = 4 Output: ["the","is","sunny","day"] Explanation: "the", "is", "sunny" and "day" are the four most frequent words, with the number of occurrence being 4, 3, 2 and 1 respectively. Constraints: 1 <= words.length <= 500 1 <= words[i].length <= 10 words[i] consists of lowercase English letters. k is in the range [1, The number of unique words[i]] Follow-up: Could you solve it in O(n log(k)) time and O(n) extra space?
Explanation
Here's a breakdown of the solution, followed by the Python code:
- Frequency Counting: Use a hash map (dictionary in Python) to count the frequency of each word in the input array. This allows for O(n) counting.
- Priority Queue (Min-Heap): Use a min-heap of size k to store the k most frequent words. The heap is ordered such that the least frequent word is at the root. If we encounter a more frequent word than the root, we replace the root and heapify. When frequencies are equal, we compare lexicographically. This ensures that lower alphabetical order words are prioritized.
Extraction and Sorting: Extract the elements from the min-heap into a list. Since the min-heap stores elements from least frequent to most frequent, we need to reverse the result to get the required order.
Runtime Complexity: O(n log k) , Storage Complexity: O(n)
Code
import heapq
from collections import Counter
def topKFrequent(words, k):
"""
Finds the k most frequent words in a list.
Args:
words: A list of strings.
k: An integer representing the number of most frequent words to return.
Returns:
A list of the k most frequent words, sorted by frequency (highest to lowest)
and then lexicographically (ascending) for words with the same frequency.
"""
# 1. Count word frequencies
counts = Counter(words)
# 2. Use a min-heap to store the k most frequent words.
# The heap stores (frequency, word) tuples. Note the negative frequency
# for min-heap ordering (smaller negative frequency means larger actual frequency).
heap = []
for word, freq in counts.items():
heapq.heappush(heap, (-freq, word)) # Negate freq for min-heap
# 3. Extract the k most frequent words from the heap and return.
result = []
for _ in range(k):
freq, word = heapq.heappop(heap)
result.append(word)
return result