Skip to content

Latest commit

 

History

History
184 lines (162 loc) · 7.35 KB

1600. Throne Inheritance.md

File metadata and controls

184 lines (162 loc) · 7.35 KB

the third one in Weekly Contest 208.


Difficulty : Medium

Related Topics : TreeDesign


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. 1.In the beginning, curOrder will be ["king"]. 2.Calling Successor(king, curOrder) will return Alice, so we append to curOrder to get ["king", "Alice"]. 3.Calling Successor(Alice, curOrder) will return Jack, so we append to curOrder to get ["king", "Alice", "Jack"]. 4.Calling Successor(Jack, curOrder) will return Bob, so we append to curOrder to get ["king", "Alice", "Jack", "Bob"]. 5.Calling 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 <= 15
  • kingName, parentName, childName, and name consist of lowercase English letters only.
  • All arguments childName and kingName are distinct.
  • All name arguments of death will be passed to either the constructor or as childName to birth first.
  • For each call to birth(parentName, childName), it is guaranteed that parentName is alive.
  • At most 10^5 calls will be made to birth and death.
  • At most 10 calls will be made to getInheritanceOrder.

Solution

  • mine
    • Java
      • Runtime: 359 ms, faster than 43.84%, Memory Usage: 111.6 MB, less than 5.18% of Java online submissions
        List<String> res;
        Map<String, List<String>> map;
        Map<String, String> parent;
        Map<String, Integer> added;
        Set<String> death;
        String kingName;
        
        public ThroneInheritance(String kingName) {
            res = new ArrayList<>();
            map = new HashMap<>();
            added = new HashMap<>();
            parent = new HashMap<>();
            death = new HashSet<>();
            this.kingName = kingName;
        }
        
        public void birth(String parentName, String childName) {
            List<String> childs = map.getOrDefault(parentName, new ArrayList<>());
            childs.add(childName);
            map.put(parentName, childs);
            parent.put(childName, parentName);
        }
        
        public void death(String name) {
            death.add(name);
        }
        
        public List<String> getInheritanceOrder() {
            added.clear();
            res.clear();
            res.add(kingName);
            while (true) {
                String last = res.get(res.size() - 1);
                check(last);
                if (last.equals(res.get(res.size() - 1))) break;
            }
        
            for (int i = res.size() - 1; i >= 0; i--) {
                if (death.contains(res.get(i))) res.remove(i);
            }
            return res;
        }
        
        
        void check(String name) {
            if (!map.containsKey(name) || map.get(name).size() == added.getOrDefault(name, 0)) {
                if (name.equals(kingName)) return;
                else {
                    if (parent.containsKey(name)) check(parent.get(name));
                }
            } else {
                if (!map.containsKey(name)) return;
        
                int index = added.getOrDefault(name, 0);
                res.add(map.get(name).get(index));
                added.put(name, index + 1);
            }
        }
        

  • the most votes
  • Runtime: 277 ms, faster than 50.82%, Memory Usage: 106 MB, less than 5.18% of Java online submissions
    String kingName;
    Map<String, List<String>> map = new HashMap<>();  // for cache children;
    Map<String, Boolean> alive = new HashMap<>();
    public ThroneInheritance(String kingName) {
        this.kingName = kingName;
    }
    
    public void birth(String pn, String cn) {
        map.computeIfAbsent(pn, k -> new ArrayList<>());
        map.get(pn).add(cn);
    }
    
    public void death(String name) {
        alive.put(name, false);
    }
    
    public List<String> getInheritanceOrder() {
        List<String> list = getList(kingName);  //all list with alive and died
        List<String> res = new ArrayList<>();
        for (String s : list)
            if (alive.getOrDefault(s, true)) res.add(s);  // remove died
        return res;
    }
    
    private List<String> getList(String p) {   // recursion to get children and build the inheritance list;
        List<String> res = new ArrayList<>();
        res.add(p);
        List<String> cs = map.getOrDefault(p, new ArrayList<>());
        for (String c : cs) {
            List<String> tmp = getList(c);
            for (String cc : tmp) res.add(cc);
        }
        return res;
    }