K Most Frequent Words Problem Statement

Given an array or list WORDS of 'N' non-empty words and an integer 'K', identify the 'K' most frequent words and return them sorted by their frequency, in descending order.

Note:
If two words share the same frequency, return them in lexicographical order.

Additionally, consider optimizing your solution to achieve O(N * logK) time complexity with O(N) additional space.

Input:

N K
word1 word2 word3 ... wordN

Output:

wordA wordB ... wordK

Example:

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

The word 'i' appears twice, as does 'love'. The other words appear only once. Hence, 'i' and 'love' are the most frequent.

Constraints:

  • 1 <= N <= 10^5
  • 1 <= K <= number of unique words

Time Limit: 1 sec

AnswerBot
4mo

Identify the K most frequent words in a list, sorted by frequency and lexicographical order.

  • Use a hashmap to store word frequencies

  • Use a min heap to keep track of K most frequent words

  • Sort the heap ba...read more

Help your peers!
Select
Add answer anonymously...

Top Software Developer Interview Questions Asked at Amazon

Q. What is OOPS?
Q. What is Java programming?
Q. Could you describe the process for designing a data structure that allows for al...read more
Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits