Python 1600.py
class ThroneInheritance:
def __init__(self, kingName: str):
self.children = defaultdict(list)
self.king = kingName
self.dead = set()
def birth(self, parentName: str, childName: str) -> None:
self.children[parentName].append(childName)
def death(self, name: str) -> None:
self.dead.add(name)
def getInheritanceOrder(self) -> List[str]:
result = []
todo = [ self.king ]
while todo:
current = todo.pop()
# next in line
if current not in self.dead:
result.append(current)
# and their kids
if current in self.children:
todo.extend(reversed(self.children[current])) # first born last so that pop() looks at them first
return result
Difficulty
and has an acceptance rate of about 68% (40k+ submissions).
Typical patterns to solve this problem:
- Depth First Search
- Design
- Hash Table
- Tree
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation models a royal succession system. It maintains a hierarchy of family members, records births and deaths, and can produce the current order of inheritance. The design relies on three core data structures: a mapping from a parent to their ordered list of children, a reference to the reigning monarch, and a set of deceased individuals. The inheritance order is generated through an iterative depth-first traversal that respects birth order while skipping those who have died.
Initialization
def __init__(self, kingName: str):
self.children = defaultdict(list)
self.king = kingName
self.dead = set()
During construction the class creates an empty defaultdict that automatically creates a list for any new parent key. The monarch’s name is stored as the root of the family tree, and a set is prepared to record deaths. Using a defaultdict eliminates the need for explicit existence checks when adding children.
Birth
def birth(self, parentName: str, childName: str) -> None:
self.children[parentName].append(childName)
A birth operation simply appends the new child’s name to the list associated with the parent. Because the list preserves insertion order, the children are kept in chronological birth order, which is essential for determining the correct succession sequence.
Death
def death(self, name: str) -> None:
self.dead.add(name)
When a person dies, their name is added to the dead set. The set provides constant-time membership checks, allowing the inheritance traversal to efficiently skip deceased members without altering the underlying family structure.
Inheritance Order Generation
def getInheritanceOrder(self) -> List[str]:
result = []
todo = [ self.king ]
while todo:
current = todo.pop()
if current not in self.dead:
result.append(current)
if current in self.children:
todo.extend(reversed(self.children[current]))
return result
The method starts with a stack (todo) containing only the monarch. It repeatedly pops the top element, adds it to the result list if the person is alive, and pushes the person’s children onto the stack in reverse order. Reversing ensures that the first-born child will be processed before later siblings because the stack’s pop operation retrieves the last element added. This loop continues until the stack is empty, yielding a complete inheritance list that respects both birth order and death exclusions.
Edge Cases Handled
The algorithm gracefully handles the death of the monarch; the king’s name remains the entry point of the traversal, but the if current not in self.dead guard prevents the dead king from appearing in the final list. It also supports families with any number of children, including zero, because the children list may be empty and the if current in self.children guard avoids unnecessary work. Deep genealogical trees are processed without recursion, preventing stack overflow in environments with limited call stack depth. Multiple deaths of the same individual are idempotent due to the set semantics, and repeated births under the same parent simply extend the existing list, preserving the chronological order automatically.
Performance Optimizations
The use of a defaultdict(list) eliminates conditional checks for parent existence during births, reducing overhead. Storing deceased members in a hash set enables O(1) look-ups when filtering the inheritance order. The iterative depth-first traversal replaces a recursive approach, thereby avoiding the overhead of function calls and the risk of exceeding recursion limits for large family trees. By extending the stack with a reversed slice of the children list, the algorithm avoids the need for additional data structures or index tracking, achieving a compact in-place traversal. The overall design ensures that each family member is visited exactly once per getInheritanceOrder call, providing efficient processing even as the hierarchy grows.
ELI5 - Simplified Explanation
Imagine a giant family tree that works like a long line for a royal crown.
First, there is a king who starts the whole family tree. The computer keeps a list of who belongs to which parent, so it knows exactly where everyone is tucked away.
When a new baby is born, the code adds their name to the list of children belonging to their parent. If someone passes away, the computer adds their name to a special list called the dead pile. This does not mean they disappear, but the crown knows to skip over them when it is time to choose the next king or queen.
To figure out who is next in line, the code starts at the very top with the king. It walks through the family by visiting the children, then the grandchildren, and then the great-grandchildren. It works a bit like a treasure hunt where it keeps track of everyone to visit.
As it travels down each branch, it looks at the name in front of it. If that person is still alive, they get a spot on the list for the crown. If they are in the dead pile, the code simply walks right past them. It keeps doing this until it has visited every single person in the family tree, making sure the order is perfect from the oldest member down to the newest baby.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | C# | TS | ||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, C#, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python |
Videos
Similar Problems
- problem 1993: Operations on Tree
Solved On The Same Day
- problem 1248: Count Number of Nice Subarrays
- problem 1358: Number of Substrings Containing All Three Characters
- problem 1371: Find the Longest Substring Containing Vowels in Even Counts
- problem 1410: HTML Entity Parser
- problem 1481: Least Number of Unique Integers after K Removals
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality