KatInterview

Frequency Tracking with Static and Streaming Top-K Retrieval

Data Structure DesignModel answer
MediumModel answerData Structure Designfrequency-countingheapssliding-window

Last updated

Build data structures to identify the most frequent elements in three scenarios: a fixed array, an unbounded stream, and a time-windowed stream.

Problem Statement

Design solutions for tracking and retrieving the most frequent elements across three different scenarios.

Part 1: Fixed Collection

You're given an array nums containing n integers and a positive integer k. Return the k values that appear most frequently in the array.

Input:

  • nums: array of integers
  • k: number of elements to return

Output: List of k most frequent values

Tie-breaking: When multiple values have the same frequency, prefer smaller values.


Part 2: Continuous Stream

Design a data structure that processes an infinite stream of integers and supports:

  • insert(value): Record one occurrence of the given value
  • query(): Return the k most frequent values seen so far

The structure should handle repeated calls to both operations efficiently.


Part 3: Time-Windowed Stream

Extend the streaming solution to handle temporal data. Events arrive as (time, value) pairs where timestamps are monotonically non-decreasing (measured in seconds).

Support these operations:

  • record(timestamp, value): Log an event
  • getTopK(timestamp): Return the k most frequent values within the time range [timestamp - 3600, timestamp] (events from the last hour, inclusive)

Requirements

  • For all three parts: if fewer than k distinct values exist, return all available values
  • Output should be deterministic and sorted by rank (most frequent first)
  • Discuss time and space complexity for each variant
  • Consider edge cases: duplicate frequencies, sparse vs. dense data, bursts of identical events

Constraints

Assume up to 200,000 operations unless you choose different bounds.

Hints

Hint 1

For the fixed array, you don't need to fully sort all distinct elements—a partial selection algorithm is more efficient.

Hint 2

In the unbounded stream, counts only go up. Can you maintain the top-k set incrementally without recalculating from scratch each time?

Hint 3

For the sliding window, think about efficient expiration: grouping events by timestamp reduces the overhead of removing old data.