Top K Frequent Words - aloalgo

Top K Frequent Words

Medium

You are given an array of strings words and an integer k.

Your task is to identify and return the k most frequent words from the input array.

Note that:

  • The order of the returned words does not matter.

Return the k most frequent words.

Example 1

Inputs
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
k = 2
Output
["apple", "banana"]
Explanation:

apple appears 3 times, banana appears 2 times, and cherry appears once. The top 2 frequent words are apple and banana.

Example 2

Inputs
words = ["dog", "cat", "dog", "bird", "cat", "dog"]
k = 2
Output
["dog", "cat"]
Explanation:

dog appears 3 times, cat appears 2 times, and bird appears once. The top 2 frequent words are dog and cat.

Loading...
Inputs
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
k = 2
Output
["apple", "banana"]

Hello! I am your ✨ AI assistant. I can provide you hints, explanations, give feedback on your code, and more. Just ask me anything related to the problem you're working on!