Registry Synced

Streaming Algorithms

133 words
1 min read

Reading compass

Now · 9.1 Reservoir Sampling

Streaming Algorithms

9.1 Reservoir Sampling

Sample kk elements uniformly from a stream of unknown length:
python
import numpy as np
def reservoir_sample(stream, k):
    reservoir = []
    for i, item in enumerate(stream):
        if i < k:
            reservoir.append(item)
        else:
            j = np.random.randint(0, i+1)
            if j < k:
                reservoir[j] = item
    return reservoir

9.2 Count-Distinct (HyperLogLog)

Estimate the number of distinct elements using O(log⁡log⁡n)O(\log \log n) space. Idea: Hash each element, track the longest run of leading zeros. If the max run is RR, estimate n≈2Rn \approx 2^R.

9.3 Heavy Hitters (Misra-Gries)

Find all elements that occur more than n/kn/k times using O(k)O(k) space. Algorithm: Maintain k−1k-1 counters. For each element, increment if tracked, else decrement all. Elements with positive counters at end are heavy hitter candidates. Join Discord PreviousFrequency EstimationNextHyperLogLog
Document outline

Keep your place and jump directly to a heading.

Table of contents

No note selected

Open a chapter to see its outline, backlinks, and sources here.