Chat app~25 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-133dfs
A chat workspace has n channels, numbered from 0. Each channel links to other channels with "see also" links, listed in order. A link works in one direction, and a channel may link to itself.
A team duplicates the workspace starting from one channel. Every channel reachable from it is copied, except shared channels, such as announcements. A copy never points to a copy of a shared channel: it points to the original.
Write duplicate_workspace(n, links, shared, start).
links[i] lists the channels that channel i links to, in order. The same channel may appear twice.shared[i] is 1 for a shared channel and 0 otherwise.start along links, depth first, taking the links of a channel in the listed order. A channel that is not shared and not yet copied is copied the first time the walk reaches it. The walk never goes through a shared channel.n, n + 1, and so on, in the order they are created.start is shared, return an empty list.Input: n = 6, links = [[1,2],[3],[3,0],[5],[0],[]], shared = [0,0,0,1,0,0], start = 0
Output: [[7, 8], [3], [3, 6]]The walk starts at channel 0 and uses a stack of the channels being read.
| Step | Channel read | Link taken | Result |
|---|---|---|---|
| 1 | 0 | start | copy of 0 is channel 6 |
| 2 | 0 | 1 | copy of 1 is channel 7, and the walk goes to 1 |
| 3 | 1 | 3 | channel 3 is shared: not copied, not entered |
| 4 | 0 | 2 | copy of 2 is channel 8, and the walk goes to 2 |
| 5 | 2 | 3, then 0 | 3 is shared, and 0 is already copied |
Channel 5 is reachable only through the shared channel 3, so it is not copied. The rows are the links of copies 6, 7 and 8: [7, 8], [3] and [3, 6].
Input: n = 6, links = [[1,2],[3],[3,0],[5],[0],[]], shared = [0,0,0,1,0,0], start = 3
Output: []The start channel is shared, so nothing is copied.
Input: n = 2, links = [[0,1],[]], shared = [0,0], start = 0
Output: [[2, 3], []]Channel 0 links to itself and to channel 1. Its copy, channel 2, links to itself and to channel 3.
1 ≤ n ≤ 100,000, and links and shared each have n entriesn - 1, and each channel has at most 400 linksshared[i] is 0 or 1, and 0 ≤ start < nLooking up each channel in the list of copies made so far costs up to n steps per link. With n = 100,000 and 150,000 links, that is about 10^10 steps. A table that maps each channel to its copy makes each lookup O(1). A chain of 100,000 channels also makes a recursive walk 100,000 calls deep, so use an explicit stack.