Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

K Most Frequent Strings

Given an array of strings words and an integer k, return the k most frequent strings.

Order the result by frequency from highest to lowest. If two strings have the same frequency, the lexicographically smaller string should come first. You may assume k is always valid (1 <= k <= the number of distinct strings).

Example 1

Input: words = ["go", "coding", "byte", "byte", "go", "interview", "go"], k = 2
Output: ["go", "byte"]
Explanation: "go" appears 3 times, "byte" appears 2 times, and
"coding" and "interview" each appear once. The two most frequent are
"go" and "byte", in that order.

Example 2

Input: words = ["a", "aa", "aaa"], k = 2
Output: ["a", "aa"]
Explanation: All three words appear exactly once, so ties are broken
lexicographically: "a" < "aa" < "aaa".

Constraints

  • 1 <= words.length <= 10^5
  • 1 <= words[i].length <= 20
  • words[i] consists of lowercase English letters.
  • k is between 1 and the number of distinct strings in words, inclusive.

Share this question

← Back to Heaps practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.