Friend Product Suggestions and Click-Path Reachability
Trees & GraphsModel answerLast updated
Two short coding tasks: suggest products that a user's friends bought but the user hasn't, and decide whether one URL can reach another through recorded navigation steps.
Answer both parts below. For each, explain your approach, give code, and state the time and space complexity.
Part 1: Suggest products from friends' purchases
A shopping platform stores these records:
type Purchase = { productId: string; amount: number; purchaseId: string };
type User = { id: string; friends: string[]; purchases: Purchase[] };
type Product = { productId: string; productName: string };
Inputs
users: every user in the system.products: the catalog, which maps eachproductIdto aproductName.targetUserId: the user who should receive suggestions.
Task
Return the names of all products that satisfy both rules:
- At least one friend of the target user has bought the product.
- The target user has never bought it.
In set terms, with P_friends the product IDs bought by any friend and P_user the product IDs bought by the target, return the names for P_friends − P_user.
Rules
- Every friend ID is guaranteed to appear in
users. - A product may appear in many purchases (by one user or several), but it must appear only once in the output.
- Output order is up to you. State it if you pick one, for example alphabetical by name.
Give the complexity in terms of U (users), F (friends of the target), T (total purchases) and P (distinct products).
Part 2: Can one page lead to another?
You have a log of navigation events with the schema:
(user_id, source_url, destination_url)
Each row says a user went to destination_url directly after source_url. Treat every distinct (source_url, destination_url) pair as a directed edge between URL nodes.
Task
Given url1 and url2, decide whether url2 can be reached from url1 by following one or more edges.
- Describe how you would build an in-memory graph from the log.
- Implement
canReach(url1, url2)returning a boolean. - Give the complexity in terms of
V(distinct URLs) andE(distinct source-to-destination pairs).
You may assume the whole log fits in memory.
Hints
Hint 1
Part 1 is a set difference. Index users by id and products by id first so every lookup is constant time, and keep the target's purchased product IDs in a set.
Hint 2
Instead of building the friends' product set and subtracting afterwards, skip any product already in the target's set while you scan each friend's purchases. Duplicates then disappear for free.
Hint 3
In Part 2 the user_id column is irrelevant. Store an adjacency map from each URL to a set of next URLs so repeated clicks do not create duplicate edges, then run a BFS with a visited set.
Hint 4
Read 'one or more edges' carefully: when url1 equals url2 the answer should be true only if url1 sits on a cycle. Seed the search with url1's direct successors and do not pre-mark url1 as visited.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Friend-based suggestions
Approach
The task is P_friends − P_user, mapped to names. Make every lookup O(1) with hash structures:
- Build
user_by_id(id to user) in one pass overusers. - Build
name_by_product(productId to name) in one pass overproducts. - Put the target's purchased product IDs in a set
owned. - For each distinct friend, loop over their purchases and add any
productIdnot inownedto a result set. - Convert IDs to names and sort, so the output is deterministic.
Filtering during the scan means the full P_friends set is never materialized. The asymptotic cost is unchanged, but memory use is a little lower.
Why it is correct
- An ID is added only if a friend bought it and the target did not, so everything returned qualifies.
- All friends' purchases are scanned, so every qualifying product is found.
- Sets collapse repeated purchases and repeated friends, so each product appears once.
- If the target appears in their own friend list, their products are already in
ownedand get excluded automatically.
Complexity
Let T_F be the number of purchases made by friends (T_F ≤ T) and K the number of suggestions (K ≤ P).
| Step | Time | Space |
|---|---|---|
| Index users | O(U) | O(U) |
| Index products | O(P) | O(P) |
| Target's purchases to set | O(T_target) | O(P) |
| Scan friends | O(F + T_F) | O(K) |
| Sort names | O(K log K) | O(K) |
Total time is O(U + P + T + K log K), or O(U + P + T) if order is irrelevant. Space is O(U + P). If a user store keyed by id already exists, the work depends only on the target's neighborhood: O(F + T_F + K log K).
Edge cases and trade-offs
- Unknown target user: return an empty list (or raise). State the choice.
- No friends, or friends with no purchases: empty result.
- A product ID missing from the catalog: skip it or fall back to the ID. State the choice.
- Two products with the same name collapse if you return a set of names. Offer
(productId, name)pairs if that matters. - A common mistake is to build
P_friendsas a list and callinon a list for the target's products, which turns the solution into O(T²).
def recommend_products(users, products, target_user_id):
user_by_id = {u.id: u for u in users}
name_by_product = {p.productId: p.productName for p in products}
target = user_by_id.get(target_user_id)
if target is None:
return []
owned = {p.productId for p in target.purchases}
rec_ids = set()
for fid in set(target.friends):
friend = user_by_id.get(fid)
if friend is None:
continue
for pur in friend.purchases:
if pur.productId not in owned:
rec_ids.add(pur.productId)
names = {name_by_product[pid] for pid in rec_ids if pid in name_by_product}
return sorted(names)
Part 2: URL reachability
Building the graph
Ignore user_id. Each row is an edge source to destination. Use an adjacency map dict[url, set[url]]. Using a set per node removes duplicate edges: many users follow the same click, so the raw row count R can be much larger than E. Construction is one pass, O(R) time and O(V + E) space.
Answering a query
Run a BFS (or iterative DFS) with a visited set, and return true the moment url2 is dequeued.
The subtle point is "one or more edges". If url1 == url2, the answer is true only when url1 lies on a cycle. To get this right, seed the queue with the direct successors of url1 and do not mark url1 as visited at the start. If url1 is later reached through a cycle, it is accepted as url2. Say this assumption aloud; if the interviewer allows zero-length paths, add if url1 == url2: return True at the top.
Why it is correct
BFS reaches every node reachable from its seeds and expands each at most once thanks to the visited set. Because the seeds are successors of url1, every dequeued node ends a path of at least one edge. The visited set also guarantees termination on cyclic graphs, which click graphs nearly always are.
Complexity
- Build: O(R) time, O(V + E) space.
- Query: O(V + E) time worst case (each node enqueued once, each edge inspected once), O(V) extra space.
- If there are many queries on a static graph, consider precomputing strongly connected components and a condensed DAG, or caching results per source, rather than rerunning BFS each time.
Edge cases
url1orurl2absent from the data: return false.- Self-loops (
a to a): handled naturally. - Very deep paths: use iterative BFS rather than recursive DFS to avoid stack overflow.
from collections import defaultdict, deque
class UrlGraph:
def __init__(self, records):
self.adj = defaultdict(set)
for _uid, src, dst in records:
self.adj[src].add(dst)
def can_reach(self, url1, url2):
if url1 not in self.adj:
return False
visited, queue = set(), deque()
for nxt in self.adj[url1]:
visited.add(nxt)
queue.append(nxt)
while queue:
node = queue.popleft()
if node == url2:
return True
for nxt in self.adj.get(node, ()):
if nxt not in visited:
visited.add(nxt)
queue.append(nxt)
return False
Common mistakes
- Skipping the visited set and looping forever on cycles.
- Treating
url1 == url2as automatically true. - Storing edges in a list, so duplicate clicks inflate memory and traversal time.
- Using recursion on a graph that may be deep.