Katkat

Support String Membership and Random Sampling

NgrokSoftware Engineer · Technical Screen

Last updated

Design an immutable in-memory string collection with exact membership checks and uniform random sampling over stored values. Combine complementary indexing and positional storage, analyze time and memory, and compare the approach with a trie for prefix sharing and future mutations.

Support String Membership and Random Sampling

Design an in-memory collection initialized from a set of strings. It must support:

  • contains(value) -> bool: report whether an exact string is present.
  • get_random() -> str: return one stored string, with every stored string equally likely.

For this practice version, strings are unique after initialization and the collection is immutable. Explain the implementation, complexity, and how your choice compares with a trie-based design.

Constraints & Assumptions

  • The collection contains at least one string.
  • Exact membership is required; prefix membership is not.
  • Total input size may be large enough that both string storage and indexing overhead matter.
  • Random sampling must be uniform across stored strings.

Clarifying Questions to Ask

  • Are duplicates possible, and if so, should sampling be uniform by distinct value or occurrence?
  • Will insertions or deletions be added later?
  • Are prefix queries expected in a future version?
  • Is a standard pseudorandom generator acceptable?

Hints

  • Membership and uniform positional sampling favor different access patterns.
  • Avoid an implementation that must traverse the entire collection for every random sample.
  • When comparing a trie, distinguish exact lookup benefits from prefix-specific benefits.

Follow-up questions

  • How would you support `insert` and `remove` while preserving uniform sampling?
  • How would sampling change if each string had a weight?
  • When could a compressed trie use less memory than storing full strings in a hash table?
  • How would you make random behavior reproducible in a unit test?