progress

~/problems / Tree techniques / Binary lifting / LCA

Earliest ancestor born since a year

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

medium ~25 min

A genealogy site stores a family forest: parent[v] (-1 if unknown) and born[v]. Parents are born strictly earlier than their children, so years decrease going up.

For a query (v, since): following parents up from v, who is the highest-up person born in since or later? If v was born before since, answer -1.

Implement earliest_since(parent, born, queries) -> list[int].

#   0 (1900) -> 1 (1930) -> 2 (1958) -> 3 (1990)
#                        -> 4 (1961)
parent = [-1, 0, 1, 2, 1]
born = [1900, 1930, 1958, 1990, 1961]
earliest_since(parent, born, [(3, 1950), (3, 1995), (4, 1930), (2, 1800)])
# [2, -1, 1, 0]

Up to 10^5 people and queries; parents needn't have smaller numbers.

⭐ Bonus: walking up one parent at a time still passes; a speed test with lines 10^5 generations deep earns a star at O(log n) per query.

Show hint

build up[j][v] (the ancestor 2^j steps up), then try j from high to low, jumping whenever the target exists and was born in since or later.

Topic: Binary lifting / LCA. up[k][v] = 2^k-th ancestor; LCA and k-th ancestor in O(log n).

0:00
Ctrl ' run · Ctrl ↵ submit
esc