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.

AdvancedInterview patternRange and stream queries

PROBLEM UNDERSTANDING

Input and expected output

Sample input
No input required
Sample output
1 2

COMPLETE C PROGRAM

Complete C implementation

ads-top-k-frequent-elements.c
Open in compiler
#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;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

1 2
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Count each value, then repeatedly select the highest remaining frequency.
  3. 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.