Space-Saving Algorithm — Top-k Frequent Items in a Stream

Keep m counters. Hit → increment. New + free slot → count 1. New + full → replace the min slot with count = min+1, recording error = min.

Per item: O(1) (Stream-Summary) Space: O(m) count − error ≤ f ≤ count

Incoming Item

press Step to process

Counters (m slots)

hit / increment min slot evicting inserting (min+1)

Step Explanation

Press Step to process one item, or Run for the whole stream.
n = 0
distinct seen = 0
min counter = 0
error bound n/m = 0

Stream-Summary (buckets by count, smallest first → O(1) min)

Big-O

OperationTimeNote
Hit (increment)O(1)move to adjacent bucket
Miss, free slotO(1)count-1 bucket
Miss, evict minO(1)head bucket (Stream-Summary)
Miss, evict (naive)O(m)min-scan
Report top-kO(m log m)sort the slots
SpaceO(m)independent of stream length

Operation Log