Chat app~20 min2s · 256 MBtarget O(n) time, O(n) spacetraversal · hashing
A chat service lets users forward a message. A forward gets a new message id, and the service records the pair of the original id and the new id as a link.
A message is forwarded at most once, and a message is the forward of at most one earlier message. A forward never leads back to an earlier message in its own chain, so no chain loops.
Moderators want the length of the longest forward chain, counted in messages. The links come in no particular order, and there can be 100,000 of them.
Write longest_chain(links).
links[i] is a pair [source, copy]: message copy is the forward of message source.Input: links = [[3, 9], [7, 3], [20, 21], [9, 4]]
Output: 4The ids 7, 3, 9 and 4 form one chain, in this order. The ids 20 and 21 form another.
| Head | Chain | Messages |
|---|---|---|
| 7 | 7, 3, 9, 4 | 4 |
| 20 | 20, 21 | 2 |
The ids 3, 9, 4 and 21 are forwards of another message, so no chain starts at them. The longest chain has 4 messages.
Input: links = []
Output: 0There are no links and so no messages.
Input: links = [[10, 11]]
Output: 2One link joins two messages.
0 ≤ links.length ≤ 100,000 (recorded forwards)1 ≤ links[i][0], links[i][1] ≤ 1,000,000,000 (message ids)Scanning the whole list to find the next link of every message costs about 10^10 steps for a chain of 100,000 links.
A table from a source to its copy finds the next message in O(1). Starting only at heads makes each message pass once, so about 200,000 steps are enough.