← 返回 linkedin 的题目列表Insert/Delete/GetRandom in O(1) with TTL per item (follow-up)
类型:online_judge
Problem: Randomized Set with TTL (follow-up)
Design a data structure that supports:
insert(x): Insert element x. Return false if x already exists; otherwise insert and return true.
remove(x): Remove element x. Return false if x does not exist; otherwise remove and return true.
getRandom(): Return a uniformly random element from the current set.
Goal: make the average time complexity as close to O(1) as possible.
Follow-up: Maintain a TTL per item
Extend the structure to support TTL (time-to-live):
insert(x, ttl): insert x with a TTL.
Once expired, an element should be treated as non-existent (must not be returned by getRandom(), and remove() should behave as if it is absent, potentially after cleanup).
Describe a design that keeps time complexity optimized, and explain how you handle expired items in:
insert(x, ttl)
remove(x)
getRandom()
Testing (asked to explain verbally)
Explain how you would test the data structure, covering at least:
Basic behavior: insert/remove/getRandom
Edge cases: calling getRandom() on an empty structure (define expected behavior)
Duplicate inserts and removing non-existing elements
Randomness: how to validate distribution statistically
TTL: near-expiry, just-expired, and many-expired scenarios
Constraints (for complexity discussion)
Up to 1e5 operations
32-bit integer values (assumptions acceptable for discussion)
Example
Input
insert 1
insert 2
getRandom
remove 1
getRandom
Output
true
true
(1 or 2)
true
2