Skip to main content
← PROBLEMS / CODING-ALGORITHM
An end-to-end domain learning journey

Top K
Frequent Elements.

Find the k most frequent integers without sorting all elements. Count occurrences, group values by frequency, and scan buckets from highest to lowest.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If latency budgets leave no room for synchronous retries, frequency cannot exceed the input length. Use that bounded range as bucket indices to select the top k in O(N) expected time and O(N) auxiliary space.

TL;DR30-second simplified summary
▾

Core Mechanics: Given an integer array nums (1 <= nums.length <= 100,000, -10,000 <= nums[i] <= 10,000) and 1 <= k <= U (where U is unique elements), we must return the k most frequent elements in strictly better than O(N log N) time.

Visual & Structural Flow: Depicts Frequency Map -> Frequency Buckets -> Descending Scan (nums (len N) -> Freq Map (U) -> Buckets [1..N] -> Result (len k)); Hash Map -> Lazy Frequency Buckets -> Early-Return Scan (Input nums[0..N-1] -> Map<val, count> -> buckets[1..N] -> Top-K Collector (stop at k)).

Trade-Offs & Production: Choosing the wrong selection strategy degrades throughput as N and k grow: 1. Execute three linear passes (O(N) expected time, O(N) auxiliary space) without mutating nums: 1.

Failure Modes & Application: Top-K heavy-hitter selection is a core building block in streaming and analytics: Real-Time Trending Topics & Hashtags: Combines local node Top-K summaries or Count-Min Sketch + min-heap.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
Database Indexing: B-Trees vs LSM-Trees
B-Trees organize sorted keys into fixed-size mutable pages optimized for fast, predictable point and range reads, whereas LSM-Trees buffer writes in memory and flush immutable sorted runs to disk for high write throughput.
Distributed & Application Caching
Caching keeps a reusable copy of data so an application can avoid repeating a database query, calculation, or network call. It can make responses faster and reduce database load. The trade-off: the copy may be out of date.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Top-K selection beats full sorting on large frequency maps.

Why this matters: The mechanism: understand how Why Top-K selection beats full sorting on large frequency maps works from first principles.

Think of Why Top-K selection beats full sorting on large frequency maps as the intuition layer for Top K Frequent Elements: The mechanism: understand how Why Top-K selection beats full sorting on large frequency maps works from first principles.

Given an integer array nums (1 <= nums.length <= 100,000, -10,000 <= nums[i] <= 10,000) and 1 <= k <= U (where U is unique elements), we must return the k most frequent elements in strictly better than O(N log N) time. Because no element can appear more than N times, frequency is bounded to [1..N]—allowing linear-time bucket selection.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Complexity gap: O(N log N) sort vs. O(N log k) heap vs. O(N) buckets.

Why this matters: The problem: see what breaks without Complexity gap: O under real concurrency or scale.

Choosing the wrong selection strategy degrades throughput as N and k grow:

  1. Full Sort (O(U log U)): Violates the < O(N log N) constraint when U ≈ N (100,000 unique values).
  2. Min-Heap of Size k (O(N + U log k)): Still pays O(U log k) comparisons when k is large (k ≈ N/2), and still requires the O(U) frequency map.
3-Pass Linear Pipeline

Frequency Map -> Frequency Buckets -> Descending Scan

nums (len N)Freq Map (U)Buckets [1..N]Result (len k)1. Pass 1: Count occurrences O(N)2. Pass 2:buckets[count].push(val) O(U)3. Pass 3: Scan N->1, stop at kO(N)

Indexing buckets by frequency (1..N) rather than element value supports negative integers and runs in O(N) expected time.

Engineering Decision Framework
Problem
How to implement Top K Frequent Elements without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
If latency budgets leave no room for synchronous retries, frequency cannot exceed the input length. Use that bounded range as bucket indices to select the top k in O(N) expected time and O(N) auxiliary space.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Top K Frequent Elements experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Common pitfalls: value-indexed buckets, shared fill([]), and boundary ties.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Three common bugs break naive implementations:

  • Indexing buckets by nums[i]: Fails on negative integers (-10,000 <= nums[i]).
  • new Array(N + 1).fill([]): Shares the exact same array reference across all N + 1 slots!
  • Pushing an entire bucket without checking result.length === k: Can return more than k elements.
Component Topology

Common pitfalls: value-indexed buckets, shared fill([]), and boundary ties

CalleringressRouter / APIcomputeProcessorstorageState Layercontrolrequestdispatchread/write
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Optimal O(N) solution: Frequency Hash Map + Bounded Bucket Array.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Execute three linear passes (O(N) expected time, O(N) auxiliary space) without mutating nums:

  1. Count (O(N)): Build Map<number, number> mapping each distinct integer to its frequency.
  2. Group by Frequency (O(U)): Allocate buckets of length nums.length + 1 (undefined slots, lazily initialized) and push num into buckets[count].
  3. Collect Top-K (O(N)): Scan freq from N down to 1, pushing elements one by one and returning immediately once result.length === k.
O(N) Bucket Selection

Hash Map -> Lazy Frequency Buckets -> Early-Return Scan

Input nums[0..N-1]Immutable;…Map<val, count>O(N) expected; U <= Nbuckets[1..N]Lazy array per freqTop-K Collector(stop at k)O(N) time, O(N) space

1.Bounded Range [1..N]: Sum of all frequencies equals N, so no count can exceed N.

2.Negative-Safe: Frequency is always >= 1, so negative input values map cleanly into buckets.

3.Early Return: Stop as soon as result.length === k without sorting the output.

Bucket selection achieves O(N) expected time and O(N) space while handling negatives and arbitrary output order.

export function topKFrequent(nums: number[], k: number): number[] {
  const frequency = new Map<number, number>();
  for (const num of nums) {
    frequency.set(num, (frequency.get(num) ?? 0) + 1);
  }

  const buckets: Array<number[] | undefined> = new Array(nums.length + 1);
  for (const [num, count] of frequency) {
    (buckets[count] ??= []).push(num);
  }

  const result: number[] = [];
  for (let freq = buckets.length - 1; freq >= 1 && result.length < k; freq--) {
    const bucket = buckets[freq];
    if (!bucket) continue;
    for (const num of bucket) {
      result.push(num);
      if (result.length === k) return result;
    }
  }
  return result;
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Top-K frequency counting scales to distributed systems.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Top-K heavy-hitter selection is a core building block in streaming and analytics:

  • Real-Time Trending Topics & Hashtags: Combines local node Top-K summaries or Count-Min Sketch + min-heap.
  • Hot-Key Detection in Caches & Kafka: Identifies skewed keys causing partition hotspots.
  • Log & Error Aggregation: Surfaces the top-k failing endpoints or stack traces per minute.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does `new Array(nums.length + 1).fill([])` introduce a bug when building frequency buckets in JavaScript/TypeScript?

Recommended Learning Flow