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
Input:
words = ["i","love","leetcode","i","love","coding"], k = 2Output:
["i","love"]Explanation:
"i" and "love" are the two most frequent words.
Input:
words = ["apple", "banana", "cherry", "apple", "banana", "apple"], k = 3Output:
["apple", "banana", "cherry"]Explanation:
"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.
Input:
words = ["cat", "dog", "bird", "cat", "fish", "dog", "ant", "bee"], k = 3Output:
["cat", "dog", "ant"]Explanation:
"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