← Questions
URL reachability from navigation records
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A table of navigation events has rows (user_id, source_url, destination_url): a user went straight from source_url to destination_url. Treat every such pair as a directed link between pages, whichever user made it. Given two URLs, decide whether you can get from the first to the second by following one or more links.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
build(records: list[tuple[str, str, str]]) -> None— loads the records into an in-memory graph. -
can_reach(url1: str, url2: str) -> bool—Trueif a path of one or more links leads fromurl1tourl2.
Example
records = [("u1", "/home", "/search"), ("u1", "/search", "/item/7"),
("u2", "/home", "/deals"), ("u3", "/item/7", "/cart"),
("u2", "/cart", "/checkout")]
can_reach("/home", "/checkout") -> True # home > search > item/7 > cart > checkout
can_reach("/deals", "/cart") -> False # nothing leaves /deals
can_reach("/checkout", "/home") -> False # links only go one way
Constraints
- All records fit in memory.
Vdistinct URLs,Edistinct links; the same link may appear in many records.
Clarifying questions
- Does
can_reach(u, u)need a loop back tou, or is it always true? - Does the user matter, or only the pages?
- Is the graph built once and queried many times?
What a strong answer covers
- An adjacency map from each URL to a set of destinations, which also removes duplicate records.
- Breadth-first or depth-first search from
url1with a visited set, so cycles between pages don't loop forever; stop early whenurl2is found. -
O(R)to build fromRrecords,O(V + E)time andO(V)extra space per query. - An iterative search for deep chains, and unknown URLs answering
False.
Follow-ups
- Return the shortest path of pages, not just yes or no.
- Many queries: precompute strongly connected components, or cache the set reachable from popular pages.
- The records don't fit in memory: how would you answer from a distributed store?
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
