Top K Frequent Words
Description
Given an array of strings words and an integer k, return the k most frequent strings. Return the answer sorted by frequency from highest to lowest. If two words have the same frequency, sort them lexicographically.
Examples
words = ["i","love","leetcode","i","love","coding"], k = 2["i","love"]"i" and "love" are the two most frequent words.
words = ["apple", "banana", "cherry", "apple", "banana", "apple"], k = 3["apple", "banana", "cherry"]"apple" appears 3 times (most frequent), "banana" appears 2 times, and "cherry" appears 1 time. Since k=3 and there are exactly 3 unique words, all words are returned sorted by frequency.
words = ["cat", "dog", "bird", "cat", "fish", "dog", "ant", "bee"], k = 3["cat", "dog", "ant"]"cat" and "dog" each appear 2 times (tied for highest frequency). Among words with frequency 1 ("bird", "fish", "ant", "bee"), "ant" comes first lexicographically. So the top 3 are: "cat", "dog" (alphabetically between tied frequencies), and "ant".
Constraints
- •
1 ≤ words.length ≤ 500 - •
1 ≤ words[i].length ≤ 10 - •
1 ≤ k ≤ unique words count
Ready to solve this problem?
Practice solo and sharpen your skills for technical interviews.