Top K Frequent Elements in a Stream
PYTHON coding challenge · Difficulty: medium · Topic: Heap / Priority Queue · +100 XP
Problem
Given a stream of integers, find the top K most frequent elements at any point in time. This problem is common in data processing systems where the frequency of events needs continuous monitoring, such as tracking the most popular queries in a search engine.
Example Input
The data below is already defined — do not redefine it.
`python
nums = [1, 1, 1, 2, 2, 3, 3, 3, 3]
k = 2
`
Expected Output
`
[3, 1]
`
Notes
- Print the result — the grader reads standard output
- Do not redefine the input; it is provided for you
What this PYTHON challenge teaches you
“Top K Frequent Elements in a Stream” is a medium-level PYTHON challenge focused on Heap / Priority Queue. Working through it gives you hands-on practice with heap, priority queue, frequency counter — the kind of transformation you are asked to write in real data engineering work and in technical interviews. You can solve it directly in the browser: the dataset is pre-loaded, so you write the query or DataFrame code, run it, and compare your output against the expected result immediately.
Concepts covered
- heap
- priority queue
- frequency counter
How to approach it
If you get stuck, work through these steps in order before looking at a full solution — each one narrows the problem down:
- 1 ≤ len(nums) ≤ 100,000
- 1 ≤ k ≤ len(nums)
- -10^9 ≤ nums[i] ≤ 10^9
- Return a list of integers — the top k frequent elements
- Expected time complexity: O(N log K) due to heap operations
How to practise it on PySpark.in
Open the challenge, write your Python code in the editor and press Run to execute it against the sample dataset. Submitting checks your output against every test case, including hidden ones, so you find out straight away whether your logic holds up. You can retry as often as you like, and each solved challenge adds to your XP.
Related PYTHON challenges
- Word Frequency Counter
- Validate Unique User IDs
- Extract Error Codes from Log Strings
- Sum of Values by Key
- Detect Anomalies in Transaction Batches
- Flatten Nested JSON Structure
Frequently asked questions
Do I need to install Spark or a database to solve this?
No. The PYTHON environment runs in your browser with the sample data already loaded, so there is nothing to install or configure.
Is this challenge free?
Yes - the problem, the sample dataset, the hints and unlimited test runs are free.
What level is it?
It is rated medium and covers Heap / Priority Queue.