Leetcode 692: Top K Frequent Words

grid47
grid47
Exploring patterns and algorithms
Aug 29, 2024 5 min read

A list of words where the most frequent ones glow softly, indicating their popularity.
Solution to LeetCode 692: Top K Frequent Words Problem

Given a list of words and an integer k, return the k most frequent words in the list. The words should be sorted by their frequency in descending order. If two words have the same frequency, they should be sorted lexicographically.
Problem
Approach
Steps
Complexity
Input: The input consists of an array of words and an integer k.
Example: words = ["apple", "banana", "apple", "orange", "banana", "banana"], k = 2
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]
Output: Return the k most frequent words sorted by frequency and lexicographical order.
Example: ["banana", "apple"]
Constraints:
Goal: The goal is to determine the k most frequent words from the given list and sort them by their frequency and lexicographical order.
Steps:
• Count the frequency of each word using a hash map.
• Sort the words first by frequency (descending) and then lexicographically.
• Return the first k words from the sorted list.
Goal: The input values are constrained as follows:
Steps:
• The number of words in the input list is between 1 and 500.
• The length of each word is between 1 and 10 characters.
• Words consist of lowercase English letters only.
• k is at most the number of unique words.
Assumptions:
• The input list is non-empty.
• There is at least one unique word in the list.
Input: Example 1: words = ["apple", "banana", "apple", "orange", "banana", "banana"], k = 2
Explanation: The words 'banana' and 'apple' are the two most frequent words. 'banana' appears 3 times and 'apple' appears 2 times, so they are returned as the result.

Input: Example 2: words = ["cat", "dog", "bird", "dog", "dog", "bird", "bird"], k = 3
Explanation: Both 'dog' and 'bird' appear 3 times, so they come first, followed by 'cat'. The result is ['dog', 'bird', 'cat'].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus