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

Be the first one to answer
Add answer anonymously...
Amazon Software Developer 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