Skip to the code
+25 XP

#91 Sample K Events From a Stream

medium

A telemetry client keeps a fair random sample of k events from a long stream. The first k events fill the reservoir in order. For each later event at index i (so i >= k), take the next number r from randoms, set j = Math.floor(r * (i + 1)), and if j < k, replace reservoir[j] with this event.

Write sampleEvents(stream, k, randoms) that returns the reservoir after the whole stream. If the stream has fewer than k events, return all of them.

Example 1

Input: stream = ["a","b","c","d","e"], k = 2, randoms = [0.5,0.9,0.2]
Output: ["a","e"]

c: j = floor(0.5 * 3) = 1, replace slot 1. d: j = 3, skip. e: j = floor(0.2 * 5) = 1, replace slot 1 again.

Example 2

Input: stream = ["x","y"], k = 3, randoms = []
Output: ["x","y"]

Fewer events than slots, so all are kept.

Constraints

  • 0 <= stream.length <= 10^5
  • 1 <= k <= 1000
  • randoms.length === Math.max(0, stream.length - k)
  • 0 <= randoms[i] < 1
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).