#1600
Throne Inheritance
MediumHash TableTreeDepth-First SearchDesignHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal solution uses a depth-first search (DFS) to traverse the family tree in a pre-order manner, ensuring we build the inheritance order efficiently without redundant checks.
⚙️
Algorithm
3 steps- 1Step 1: Create a tree structure to represent the family.
- 2Step 2: Use a DFS function to traverse the tree and add each alive person to the inheritance order.
- 3Step 3: Return the complete inheritance order.
solution.py30 lines
1class Person:
2 def __init__(self, name):
3 self.name = name
4 self.children = []
5 self.is_alive = True
6
7class ThroneInheritance:
8 def __init__(self, kingName):
9 self.king = Person(kingName)
10 self.people = {kingName: self.king}
11
12 def birth(self, parentName, childName):
13 parent = self.people[parentName]
14 child = Person(childName)
15 child.parent = parent
16 parent.children.append(child)
17 self.people[childName] = child
18
19 def death(self, name):
20 self.people[name].is_alive = False
21
22 def getInheritanceOrder(self):
23 order = []
24 def dfs(person):
25 if person.is_alive:
26 order.append(person.name)
27 for child in person.children:
28 dfs(child)
29 dfs(self.king)
30 return orderℹ
Complexity note: The time complexity is O(n) because we visit each person exactly once during the DFS traversal. The space complexity is O(n) due to the storage of the order list and the recursion stack.
- 1The order of inheritance is a pre-order traversal of the family tree.
- 2Handling births and deaths dynamically requires careful management of the tree structure.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.