ADVANCED DATA STRUCTURES PROGRAM • LEVEL 21 — PLACEMENT-ORIENTED STRUCTURES
Select the Top-K Frequent Elements
Learn how to select the top-k frequent elements using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
No input required
Sample output
1 2
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int values[]={1,1,1,2,2,3},frequency[4]={0};for(int i=0;i<6;i++)frequency[values[i]]++;for(int pick=0;pick<2;pick++){int best=1;for(int value=2;value<=3;value++)if(frequency[value]>frequency[best])best=value;printf("%d%c",best,pick==1?'\n':' ');frequency[best]=-1;}return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
1 2
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Count each value, then repeatedly select the highest remaining frequency.
- Display the computed result.
Count each value, then repeatedly select the highest remaining frequency.
EFFICIENCY
Time and space complexity
Time complexity
O(n + uk) demonstration
Auxiliary space
O(u)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
