Maps app~30 min2s · 256 MBtarget O(n) time, O(n) spaceclassic twin: lc-968tree-recursion · dp
A hiking app maps a trail network as a tree of junctions. Junction 0 is the trailhead. From each junction at most two trails lead on, a left one and a right one, and each leads to a new junction.
A signal tower at a junction gives coverage to that junction, to the junction before it, and to the junctions its trails lead to. Your team lead wants every junction covered, with as few towers as possible.
Write fewest_towers(left, right).
0 to n - 1, and junction 0 is the trailhead. There is at least one junction.left[i] and right[i] are the junctions that the trails from junction i lead to, or -1 where there is none.i covers i, the junction whose trail leads to i, and the junctions left[i] and right[i].Input: left = [1, 3, -1, 5, -1, 6, -1], right = [2, 4, -1, -1, -1, -1, -1]
Output: 3The trailhead 0 leads to 1 and 2. Junction 1 leads to 3 and 4. A single trail runs on from 3 to 5 and from 5 to 6.
Decide from the bottom up. Every junction ends in one of three states: it holds a tower, it is covered without one, or it is not covered yet.
A junction puts a tower in when a junction below it is not covered yet. Otherwise it is covered if a junction below holds a tower. If not, it waits to be covered from above.
| Junction | States below | Result | Towers so far |
|---|---|---|---|
6 |
none | not covered | 0 |
5 |
6 is not covered |
tower | 1 |
4 |
none | not covered | 1 |
3 |
5 holds a tower |
covered | 1 |
2 |
none | not covered | 1 |
1 |
3 covered, 4 not covered |
tower | 2 |
0 |
1 holds a tower, 2 not covered |
tower | 3 |
Towers at 5, 1 and 0 cover every junction.
Input: left = [1, -1, -1], right = [2, -1, -1]
Output: 1A tower at the trailhead covers itself and both of the junctions its trails lead to.
Input: left = [-1], right = [-1]
Output: 1One junction needs its own tower.
1 ≤ length of left = length of right ≤ 10^5left and right is -1 or a junction number from 1 to n - 10There are up to 2^100000 sets of towers, so trying every set is not possible. A solution has to handle each junction once.
A trail network shaped like a chain makes nested calls 100,000 deep, more than Python allows by default. Use a loop over a list of the junctions instead of recursion. The answer is at most n, so a 32-bit integer holds it.