Timeline Lookup Store and Shared-Friend Suggestions
Data Structure DesignModel answerLast updated
Build a store that returns the latest value at or before a query time, then suggest new connections to a user based on having at least two friends in common.
This exercise has two independent parts. Explain your approach, state your assumptions, and write the code for each.
Part 1: A store that remembers history
Design a class TimelineStore that records values for keys together with the moment each value was written, and can answer "what was the value of this key at time t?"
put(key, value, timestamp)recordsvalueforkeyas oftimestamp.get(key, timestamp)returns the value whose write time is the largest one that is less than or equal totimestamp. If the key has no write at or before that time, or the key is unknown, returnNone.
Example:
store = TimelineStore()
store.put('a', 'v1', 10)
store.put('a', 'v2', 20)
store.get('a', 15) # 'v1'
store.get('a', 25) # 'v2'
store.get('a', 5) # None
Requirements:
- Timestamps are non-negative integers.
- Lookups should take logarithmic time in the number of versions of a key.
- Keep the API clean. Say what happens when the same key and timestamp are written twice, and what happens if writes arrive out of chronological order.
Part 2: Suggesting new connections
Write get_recommendations(user_id, friendships), where friendships is a list of pairs (u1, u2) describing an undirected friendship graph.
A user x is a suggestion for user_id if:
xis notuser_idand is not already a direct friend ofuser_id, andxhas at least two friends in common withuser_id.
Example: A is friends with B and C; B and C are both friends with D; A and D are not friends. Then D is a suggestion for A, because B and C are shared friends.
Discuss duplicate edges, self-loops, users who are absent from the graph, and the order in which you return results. Give the time complexity.
Follow-ups to consider
- How would Part 1 change if there are very many out-of-order writes for a single key, or the history does not fit in memory?
- What changes if suggestions should be found within three hops instead of two?
Hints
Hint 1
For Part 1, keep per key a sorted list of timestamps next to a list of values at matching positions. The answer to a query is the entry just before the first timestamp that is strictly greater than the query time.
Hint 2
Decide up front how to treat a duplicate (key, timestamp) write and an out-of-order write. A plain append handles the common in-order case, and a binary-search insert handles the rest.
Hint 3
For Part 2, build adjacency sets, then for each friend of the target walk that friend's friends and increment a counter. Skip the target and anyone already a direct friend, then keep counters of 2 or more.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Overview
The two parts are unrelated. Part 1 is about choosing an index that supports "latest at or before t" queries and handling boundaries correctly. Part 2 is a two-hop graph walk with counting.
Part 1: TimelineStore
Assumptions to state
- Same key and timestamp written twice: the later write overwrites the earlier one.
- Out-of-order writes: supported, but optimized for the common case where timestamps increase.
- Query earlier than every version, or unknown key: return
None.
Approach
For each key, keep two parallel lists: timestamps (sorted, no duplicates) and values (aligned by index).
A query at time t wants the rightmost timestamp that is <= t. With bisect_right(timestamps, t) giving the first index whose timestamp is strictly greater than t, the answer sits at index bisect_right(...) - 1. If that index is -1, no version qualifies.
Parallel lists beat a list of (timestamp, value) tuples because we can bisect directly on integers, and values never need to be comparable.
Why it works
The invariant is that timestamps stays sorted and unique. put keeps it by appending when the timestamp is newer than the last one, overwriting when it already exists, and otherwise inserting at the bisect_left position. Given a sorted list, bisect_right splits it into entries <= t and entries > t, so the last entry of the first group is exactly the largest timestamp not exceeding t.
Complexity
| Operation | Time |
|---|---|
get | O(log n), n = versions of that key |
put, in order | amortized O(1) |
put, out of order | O(log n) search + O(n) shift |
| Space | O(total puts) |
Code
from bisect import bisect_left, bisect_right
from collections import defaultdict
class TimelineStore:
def __init__(self):
self._ts = defaultdict(list)
self._vals = defaultdict(list)
def put(self, key, value, timestamp):
ts, vals = self._ts[key], self._vals[key]
if not ts or timestamp > ts[-1]:
ts.append(timestamp)
vals.append(value)
return
i = bisect_left(ts, timestamp)
if ts[i] == timestamp:
vals[i] = value
else:
ts.insert(i, timestamp)
vals.insert(i, value)
def get(self, key, timestamp):
ts = self._ts.get(key)
if not ts:
return None
i = bisect_right(ts, timestamp) - 1
return self._vals[key][i] if i >= 0 else None
Use .get(key) in get rather than indexing the defaultdict, otherwise merely reading unknown keys creates empty entries.
Edge cases
Unknown key, query before the first version, query exactly equal to a stored timestamp (inclusive, hence bisect_right), duplicate timestamp, and timestamp 0.
Part 2: Shared-friend suggestions
Approach
- Build an undirected adjacency map of sets, ignoring self-loops. Sets make duplicate input pairs harmless.
- For every friend
fof the target, iterate overf's friendsg. Each suchgreceives one credit, representing the mutual friendf. - Skip
gif it is the target or already a direct friend. - Keep candidates whose count is at least 2.
Return them sorted by mutual-friend count descending, then by id. The problem only needs the set, but a ranked, deterministic order is what a real recommender would want, and it makes testing easy.
Why the counts are right
A candidate g is reached through f exactly when f is adjacent to both the target and g, which is the definition of a mutual friend. Each mutual friend is visited once in the outer loop and adds exactly one credit, so count[g] equals the true number of mutual friends. Filtering out the target and its direct friends enforces the "not already a friend" rule.
Complexity
- Building the graph: O(E) time, O(V + E) space.
- Two-hop walk: O(sum of deg(f) over friends f of the target), bounded by O(E) and roughly O(d²) for average degree d.
- Sorting: O(k log k) for k candidates.
Code
from collections import defaultdict, Counter
def get_recommendations(user_id, friendships):
graph = defaultdict(set)
for u, v in friendships:
if u != v:
graph[u].add(v)
graph[v].add(u)
friends = graph.get(user_id, set())
mutual = Counter()
for f in friends:
for g in graph[f]:
if g != user_id and g not in friends:
mutual[g] += 1
result = [c for c, n in mutual.items() if n >= 2]
result.sort(key=lambda c: (-mutual[c], c))
return result
Edge cases
- Target has no friends or is absent: return
[]. - Self-loops and duplicate edges in either orientation: no effect.
- Exactly one mutual friend: excluded.
- In the example, D is reached via B and via C, so its count is 2 and it is returned.
Follow-ups
Heavy or out-of-order writes
The list-based design only suffers when out-of-order inserts shift O(n) elements. Options:
- In memory: a balanced BST, skip list, or
sortedcontainers.SortedListgives O(log n) inserts and floor queries. - Too large for memory: a B+-tree or LSM store keyed by
(key, timestamp), where a floor query is a reverse seek from(key, t). This is the pattern behind multi-version storage engines. - Bounded growth: keep only the last N versions or drop versions older than a TTL, optionally with periodic snapshots.
Three-hop suggestions
The frontier grows to roughly O(d³), around a million nodes at d = 100, and hub users make it worse. You must switch to BFS with a visited set so each node gets its shortest distance, and decide what "mutual" means at distance three. In practice, cap fan-out, sample high-degree nodes, or precompute offline.
Common mistakes
- Using
bisect_left, which breaks the inclusive "at or equal to" rule. - Forgetting to exclude the target or its direct friends from the counter.
- Counting a candidate once per path rather than once per distinct mutual friend, which duplicate edges would cause with lists instead of sets.
- Creating empty entries on read by indexing a
defaultdict.