KatInterview

Timeline Lookup Store and Shared-Friend Suggestions

Data Structure DesignModel answer
MediumModel answerData Structure Designbinary-searchhash-mapgraph

Last 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) records value for key as of timestamp.
  • get(key, timestamp) returns the value whose write time is the largest one that is less than or equal to timestamp. If the key has no write at or before that time, or the key is unknown, return None.

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:

  • x is not user_id and is not already a direct friend of user_id, and
  • x has at least two friends in common with user_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.