Engineering platform~20 min2s · 256 MBtarget O(n + m) time, O(n + m) spaceclassic twin: lc-133bfs
The build system of an app can fork a workspace into a sandbox. Package 0 is the root. Each package lists the packages it depends on, and dependencies may be shared, or may even refer back to a package higher up.
Your team lead says: "Copy the root and everything it needs into a fresh workspace. Number the copies in the order a breadth first search meets them, and make every copy point at copies, never at the originals."
You write the copier. Packages that the root does not need are left out.
Write clone_workspace(deps).
deps[i] lists the packages that package i depends on, in order. The number of packages is len(deps).0 and every package that can be reached from it through dependencies. Copy 0 is the copy of package 0.k lists the copy numbers of the dependencies of copy k, in the original order. The original deps must not change.A package may depend on itself, on a package that depends on it, or on the same package twice.
Input: deps = [[3, 1], [0], [3, 5], [2, 0], [1], [4]]
Output: [[1, 2], [3, 0], [0], [1, 4], [5], [2]]The search keeps a queue of packages whose copies are not yet written. A package gets its copy number the first time it is met.
| Package taken | Its copy | Row written | New copy numbers |
|---|---|---|---|
| 0 | 0 | [1, 2] | 3 gets 1, 1 gets 2 |
| 3 | 1 | [3, 0] | 2 gets 3 |
| 1 | 2 | [0] | none |
| 2 | 3 | [1, 4] | 5 gets 4 |
| 5 | 4 | [5] | 4 gets 5 |
| 4 | 5 | [2] | none |
The copies are numbered 0 to 5 in the order met. Every row uses copy numbers, so the new workspace never points at an original.
Input: deps = [[0]]
Output: [[0]]A package that depends on itself is copied once, and its copy depends on itself.
Input: deps = [[], [0]]
Output: [[]]Package 1 depends on the root, but the root does not depend on it, so it is left out.
1 ≤ len(deps) ≤ 100,000deps[i] is a package number from 0 to len(deps) - 1There can be 100,000 packages and 200,000 dependencies. Copying each package once and each dependency once takes about 300,000 steps. Looking each dependency up by scanning a list of the packages found so far takes up to 200,000 times 100,000 steps, which is 20 billion.