×

Instructions

Please read the instructions carefully before starting the exam.

Once you start the exam, the timer will begin, and you cannot pause it.

Ensure that you complete and submit your code within the given time if the timer is enabled.


Top K Frequent Words – Heap (Difficulty - Medium)


Top K Frequent Words – Heap Based Problem

Problem Statement:

Given a list of words representing search or action logs, your task is to return the top k most frequent words using a Heap structure.

If multiple words have the same frequency, return them in lexicographical order (dictionary order).

You must solve this using a Heap (e.g., PriorityQueue in Java). Sorting all words directly is not allowed due to performance constraints.

Input:

  • words: A single string that represents a list of lowercase words (1 ≤ words.length ≤ 10⁵)
  • k: An integer (1 ≤ k ≤ total unique words)
  • Format: [word1, word2, ..., wordN], k = X

Output:

A single string representing a list of the top k frequent words in required order:

[wordX, wordY, ..., wordK]

Constraints:

  • 1 ≤ total words ≤ 10⁵
  • Words consist of lowercase English letters only
  • Return exactly k words

Example 1:

input: [data, science, data, ai, ai, code], k = 3
output: [ai, data, code]

Explanation:
Both ai and data appear twice. ai is lexicographically smaller.
code and science appear once — code comes before science.
    

Example 2:

input: [hello, world, hello, java, java, python, hello], k = 2
output: [hello, java]

Explanation:
hello appears 3 times, java appears twice.
    

Example 3:

input: [zebra, apple, banana, apple, zebra, banana, zebra], k = 2
output: [zebra, apple]

Explanation:
zebra: 3 times, apple and banana: 2 each.
Between apple and banana, apple comes first.
    

Example 4:

input: [chat, chat, bot, bot, bot, ai, ai, data], k = 3
output: [bot, ai, chat]

Explanation:
bot appears 3 times, ai and chat appear 2 times.
Lexicographical order of tie: ai < chat.
    


Time Left:



Processing...

Error:


                

Output:

Test Case Result Input Correct Output Your Output




Submission Result