Search~25 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-2385tree-recursion · bfs
A search app keeps its pages in an index tree. Page 0 is the top, and each page links down to at most two pages, a left one and a right one.
When a page is marked stale, one minute later every page linked to it is marked stale as well. That means the pages below it and the page above it. One page starts out stale. Your team lead asks: how many minutes pass until every page is stale?
Write minutes_until_all_stale(left, right, start).
0 to n - 1, and page 0 is the top. There is at least one page.left[i] and right[i] are the pages that page i links down to, or -1 where there is none.start is the page that is stale at minute 0.Input: left = [1, 3, 5, -1, 6, -1, -1, -1], right = [2, 4, -1, -1, 7, -1, -1, -1], start = 3
Output: 4Page 0 links down to 1 and 2. Page 1 links to 3 and 4, page 2 to 5, and page 4 to 6 and 7.
The mark spreads in all directions, so the number of minutes is the distance from page 3 to the farthest page. Spread one step at a time and record the minute when each page turns stale.
| Minute | Pages that turn stale | Pages stale so far |
|---|---|---|
| 0 | 3 |
1 |
| 1 | 1 |
2 |
| 2 | 0, 4 |
4 |
| 3 | 2, 6, 7 |
7 |
| 4 | 5 |
8 |
All 8 pages are stale at minute 4.
Input: left = [1, -1], right = [-1, -1], start = 1
Output: 1Page 1 is below page 0. The mark goes up one link, to the top page, in one minute.
Input: left = [-1], right = [-1], start = 0
Output: 0The only page is stale from the start.
1 ≤ length of left = length of right ≤ 10^5left and right is -1 or a page number from 1 to n - 10 ≤ start < n0Simulating the spread by scanning every page once per minute costs n steps a minute. A long chain of pages takes up to 100,000 minutes, so that is about 10^10 steps.
A chain also makes nested calls 100,000 deep, more than Python allows by default. Spread with a queue, handling each page once. The answer is below n, so a 32-bit integer holds it.