K Most Frequent Words Problem Statement

Given an array of N non-empty words and an integer K, return the K most frequent words sorted by their frequency from highest to lowest.

Example:

Input:
N = 6, K = 2
words = ["i", "love", "leetcode", "i", "love", "coding"]
Output:
["i", "love"]
Explanation:

The words "i" and "love" appear twice and are most frequent. The word "leetcode" appears once.

Constraints:

  • 1 <= N <= 105
  • 1 <= K <= number of unique words
  • Words consist of only lowercase letters.
Note:

If two words have the same frequency, the lexicographically smaller word comes first.

Follow up:

Try solving it in O(N * logK) time and O(N) extra space.

AnswerBot
1y

Given an array of words and an integer k, return the k most frequent words sorted by frequency.

  • Use a hashmap to count the frequency of each word

  • Use a priority queue to keep track of the k most frequen...read more

Help your peers!
Add answer anonymously...
Atlassian SDE-2 Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter