Mutating counts without cleanup
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Move from brute-force thinking to an efficient approach using hash map strategy.
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.
curOrder will be ["king"].Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"].Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"].Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"].Successor(Bob, curOrder) will return null. 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 the ThroneInheritance class. The name of the king is given as part of the constructor.void birth(string parentName, string childName) Indicates that parentName gave birth to childName.void death(string name) Indicates the death of name. The death of the person doesn't affect the Successor function 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, and name consist of lowercase English letters only.childName and kingName are distinct.name arguments of death will be passed to either the constructor or as childName to birth first.birth(parentName, childName), it is guaranteed that parentName is alive.105 calls will be made to birth and death.10 calls will be made to getInheritanceOrder.Problem summary: 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, curOrder will be ["king"]. Calling Successor(king, curOrder) will return Alice, so we
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Hash Map · Tree · Design
["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]]
operations-on-tree)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1600: Throne Inheritance
class ThroneInheritance {
private String king;
private Set<String> dead = new HashSet<>();
private Map<String, List<String>> g = new HashMap<>();
private List<String> ans = new ArrayList<>();
public ThroneInheritance(String kingName) {
king = kingName;
}
public void birth(String parentName, String childName) {
g.computeIfAbsent(parentName, k -> new ArrayList<>()).add(childName);
}
public void death(String name) {
dead.add(name);
}
public List<String> getInheritanceOrder() {
ans.clear();
dfs(king);
return ans;
}
private void dfs(String x) {
if (!dead.contains(x)) {
ans.add(x);
}
for (String y : g.getOrDefault(x, List.of())) {
dfs(y);
}
}
}
/**
* Your ThroneInheritance object will be instantiated and called as such:
* ThroneInheritance obj = new ThroneInheritance(kingName);
* obj.birth(parentName,childName);
* obj.death(name);
* List<String> param_3 = obj.getInheritanceOrder();
*/
// Accepted solution for LeetCode #1600: Throne Inheritance
type ThroneInheritance struct {
king string
dead map[string]bool
g map[string][]string
}
func Constructor(kingName string) ThroneInheritance {
return ThroneInheritance{kingName, map[string]bool{}, map[string][]string{}}
}
func (this *ThroneInheritance) Birth(parentName string, childName string) {
this.g[parentName] = append(this.g[parentName], childName)
}
func (this *ThroneInheritance) Death(name string) {
this.dead[name] = true
}
func (this *ThroneInheritance) GetInheritanceOrder() (ans []string) {
var dfs func(string)
dfs = func(x string) {
if !this.dead[x] {
ans = append(ans, x)
}
for _, y := range this.g[x] {
dfs(y)
}
}
dfs(this.king)
return
}
/**
* Your ThroneInheritance object will be instantiated and called as such:
* obj := Constructor(kingName);
* obj.Birth(parentName,childName);
* obj.Death(name);
* param_3 := obj.GetInheritanceOrder();
*/
# Accepted solution for LeetCode #1600: Throne Inheritance
class ThroneInheritance:
def __init__(self, kingName: str):
self.king = kingName
self.dead = set()
self.g = defaultdict(list)
def birth(self, parentName: str, childName: str) -> None:
self.g[parentName].append(childName)
def death(self, name: str) -> None:
self.dead.add(name)
def getInheritanceOrder(self) -> List[str]:
def dfs(x: str):
x not in self.dead and ans.append(x)
for y in self.g[x]:
dfs(y)
ans = []
dfs(self.king)
return ans
# Your ThroneInheritance object will be instantiated and called as such:
# obj = ThroneInheritance(kingName)
# obj.birth(parentName,childName)
# obj.death(name)
# param_3 = obj.getInheritanceOrder()
// Accepted solution for LeetCode #1600: Throne Inheritance
use std::collections::HashMap;
use std::collections::HashSet;
struct ThroneInheritance {
root: String,
nodes: HashMap<String, Vec<String>>,
dead: HashSet<String>,
}
impl ThroneInheritance {
fn new(root: String) -> Self {
let nodes = HashMap::new();
let dead = HashSet::new();
ThroneInheritance { root, nodes, dead }
}
fn birth(&mut self, parent_name: String, child_name: String) {
self.nodes.entry(parent_name).or_default().push(child_name);
}
fn death(&mut self, name: String) {
self.dead.insert(name);
}
fn get_inheritance_order(&self) -> Vec<String> {
let mut res = vec![];
self.dfs(&self.root, &mut res);
res
}
fn dfs(&self, name: &str, all: &mut Vec<String>) {
if !self.dead.contains(name) {
all.push(name.to_string())
}
for child in self.nodes.get(name).unwrap_or(&vec![]) {
self.dfs(child, all);
}
}
}
#[test]
fn test() {
let mut t = ThroneInheritance::new("king".to_string());
t.birth("king".to_string(), "andy".to_string());
t.birth("king".to_string(), "bob".to_string());
t.birth("king".to_string(), "catherine".to_string());
t.birth("andy".to_string(), "matthew".to_string());
t.birth("bob".to_string(), "alex".to_string());
t.birth("bob".to_string(), "asha".to_string());
let order = t.get_inheritance_order();
assert_eq!(
order,
vec_string![
"king",
"andy",
"matthew",
"bob",
"alex",
"asha",
"catherine"
]
);
t.death("bob".to_string());
let order = t.get_inheritance_order();
assert_eq!(
order,
vec_string!["king", "andy", "matthew", "alex", "asha", "catherine"]
);
}
// Accepted solution for LeetCode #1600: Throne Inheritance
class ThroneInheritance {
private king: string;
private dead: Set<string> = new Set();
private g: Map<string, string[]> = new Map();
constructor(kingName: string) {
this.king = kingName;
}
birth(parentName: string, childName: string): void {
this.g.set(parentName, this.g.get(parentName) || []);
this.g.get(parentName)!.push(childName);
}
death(name: string): void {
this.dead.add(name);
}
getInheritanceOrder(): string[] {
const ans: string[] = [];
const dfs = (x: string) => {
if (!this.dead.has(x)) {
ans.push(x);
}
for (const y of this.g.get(x) || []) {
dfs(y);
}
};
dfs(this.king);
return ans;
}
}
/**
* Your ThroneInheritance object will be instantiated and called as such:
* var obj = new ThroneInheritance(kingName)
* obj.birth(parentName,childName)
* obj.death(name)
* var param_3 = obj.getInheritanceOrder()
*/
Use this to step through a reusable interview workflow for this problem.
BFS with a queue visits every node exactly once — O(n) time. The queue may hold an entire level of the tree, which for a complete binary tree is up to n/2 nodes = O(n) space. This is optimal in time but costly in space for wide trees.
Every node is visited exactly once, giving O(n) time. Space depends on tree shape: O(h) for recursive DFS (stack depth = height h), or O(w) for BFS (queue width = widest level). For balanced trees h = log n; for skewed trees h = n.
Review these before coding to avoid predictable interview regressions.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.