Top K Frequent Elements using Priority Queue

Hard STL Containers
Solve in Playground →

Problem Statement

Write a C++ program using frequency maps and `std::priority_queue` to find the K most frequent elements.

Input Format

First line: N and K. Second line: N space-separated integers.

Output Format

Print K most frequent elements separated by a space.

Constraints

1 <= K <= N <= 1000

Sample Input

6 2
1 1 1 2 2 3

Sample Output

1 2

Explanation

Combines hash frequency mapping with min-heaps/priority queues to compute top-K rankings efficiently.

Starter Code

#include <iostream>
#include <vector>
#include <unordered_map>
#include <queue>
#include <algorithm>

int main() {
    int n, k;
    if (std::cin >> n >> k) {
        // Write your frequency mapping and min-heap top-K logic here

    }
    return 0;
}

Limits

  • Time Limit: 1s
  • Memory Limit: 256MB

Embedded C Programming

Updated: March 15, 2026
Intermediate

Embedded systems rely on efficient low-level programming to interact directly with hardware. In this course, you will learn how to write practical Embedded C programs used in real microcontroller-based systems. Rather than focusing only on theory, this course follows a practice-driven approach. Each lesson includes hands-on coding exercises that simulate real firmware development tasks used