Graph Theory37 sections · 1633 units
Open in Course

Handling Multiple Children (Prefix-suffix pattern)

(Sibling combination)

Node uu has children c1,c2,,ckc_1, c_2, \ldots, c_k. To compute up[c_i], you need the combined contribution of all children except cic_i. Naively recomputing this for each child takes O(k2)O(k^2) time. Build prefix array: pref[i] = combine(down[c_1], ..., down[c_i]). Build suffix array: suff[i] = combine(down[c_i], ..., down[c_k]).

These take O(k)O(k) time to build. Then for child cic_i, the contribution of other children is combine(pref[i-1], suff[i+1]). You get all kk values in O(k)O(k) total time. This only works when combine is associative.

Space complexity is O(n)O(n) for the data structures used.