Throne Inheritance Problem
Description
LeetCode Problem 1600.
A kingdom consists of a king, his children, his grandchildren, and so on. Every once in a while, someone in the family dies or a child is born.
The kingdom has a well-defined order of inheritance that consists of the king as the first member. Let's define the recursive function Successor(x, curOrder), which given a person x and the inheritance order so far, returns who should be the next person after x in the order of inheritance.
Successor(x, curOrder):
if x has no children or all of x's children are in curOrder:
if x is the king return null
else return Successor(x's parent, curOrder)
else return x's oldest child who's not in curOrder
For example, assume we have a kingdom that consists of the king, his children Alice and Bob (Alice is older than Bob), and finally Alice's son Jack.
- In the beginning,
curOrderwill be["king"]. - Calling
Successor(king, curOrder)will return Alice, so we append tocurOrderto get["king", "Alice"]. - Calling
Successor(Alice, curOrder)will return Jack, so we append tocurOrderto get["king", "Alice", "Jack"]. - Calling
Successor(Jack, curOrder)will return Bob, so we append tocurOrderto get["king", "Alice", "Jack", "Bob"]. - Calling
Successor(Bob, curOrder)will returnnull. Thus the order of inheritance will be["king", "Alice", "Jack", "Bob"].
Using the above function, we can always obtain a unique order of inheritance.
Implement the ThroneInheritance class:
ThroneInheritance(string kingName)Initializes an object of theThroneInheritanceclass. The name of the king is given as part of the constructor.void birth(string parentName, string childName)Indicates thatparentNamegave birth tochildName.void death(string name)Indicates the death ofname. The death of the person doesn't affect theSuccessorfunction nor the current inheritance order. You can treat it as just marking the person as dead.string[] getInheritanceOrder()Returns a list representing the current order of inheritance excluding dead people.
Example 1:
Input
["ThroneInheritance", "birth", "birth", "birth", "birth", "birth", "birth", "getInheritanceOrder", "death", "getInheritanceOrder"]
[["king"], ["king", "andy"], ["king", "bob"], ["king", "catherine"], ["andy", "matthew"], ["bob", "alex"], ["bob", "asha"], [null], ["bob"], [null]]
Output
[null, null, null, null, null, null, null, ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"], null, ["king", "andy", "matthew", "alex", "asha", "catherine"]]
Explanation
ThroneInheritance t= new ThroneInheritance("king"); // order: king
t.birth("king", "andy"); // order: king > andy
t.birth("king", "bob"); // order: king > andy > bob
t.birth("king", "catherine"); // order: king > andy > bob > catherine
t.birth("andy", "matthew"); // order: king > andy > matthew > bob > catherine
t.birth("bob", "alex"); // order: king > andy > matthew > bob > alex > catherine
t.birth("bob", "asha"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "bob", "alex", "asha", "catherine"]
t.death("bob"); // order: king > andy > matthew > bob > alex > asha > catherine
t.getInheritanceOrder(); // return ["king", "andy", "matthew", "alex", "asha", "catherine"]
Constraints:
1 <= kingName.length, parentName.length, childName.length, name.length <= 15kingName,parentName,childName, andnameconsist of lowercase English letters only.- All arguments
childNameandkingNameare distinct. - All
namearguments ofdeathwill be passed to either the constructor or aschildNametobirthfirst. - For each call to
birth(parentName, childName), it is guaranteed thatparentNameis alive. - At most
10^5calls will be made tobirthanddeath. - At most
10calls will be made togetInheritanceOrder.
Solution
Approach: Preorder Traversal of the Family Tree
Look at what Successor does: from a person it goes to their oldest child not yet listed; when all children are listed it goes back up to the parent and tries the next child there. That is exactly a preorder traversal of the family tree: list a person, then the subtrees of their children from oldest to youngest.
So we only need to store the tree:
children: a hash map from each name to the list of their children in birth order.birthappends to it.dead: a set of names.deathadds to it. A death does not change the tree (the problem says it doesn't affectSuccessor), so a dead person's descendants keep their places; we just leave the dead person out of the result.
getInheritanceOrder walks the tree in preorder from the king and skips the names in dead.
The tricky part is depth: births can form one long line (each child having a child), up to 105 generations, which would overflow a recursive walk. So we use an explicit stack: pop a person, add them if alive, and push their children from youngest to oldest so the oldest is popped next.
Complexity: birth and death take O(1) time; getInheritanceOrder takes O(n) time, where n is the number of people. O(n) space.
class ThroneInheritance:
def __init__(self, kingName: str):
self.king = kingName
self.children = {} # name -> children in birth order (oldest first)
self.dead = set()
def birth(self, parentName: str, childName: str) -> None:
self.children.setdefault(parentName, []).append(childName)
def death(self, name: str) -> None:
self.dead.add(name) # the tree keeps the person; they are only skipped in the order
def getInheritanceOrder(self) -> List[str]:
# Preorder walk of the family tree with an explicit stack (a long line of births is deep).
order = []
stack = [self.king]
while stack:
name = stack.pop()
if name not in self.dead:
order.append(name)
# Push the youngest child first so the oldest one is popped next.
stack.extend(reversed(self.children.get(name, [])))
return order