Employee Importance

medium bfs dfs hash map

Problem

Each Employee has id, importance, and list of subordinate ids. Sum the importance of an employee and all (transitive) subordinates.

Inputemployees=[[1,5,[2,3]],[2,3,[]],[3,3,[]]] id=1
Output11
5 + 3 + 3 = 11.

def get_importance(emps, eid):
    by_id = {e[0]: e for e in emps}
    total = 0; q = [eid]
    while q:
        e = by_id[q.pop()]; total += e[1]; q.extend(e[2])
    return total
function getImportance(emps, eid) {
  const m = new Map(emps.map(e => [e[0], e]));
  let total = 0; const q = [eid];
  while (q.length) { const e = m.get(q.pop()); total += e[1]; q.push(...e[2]); }
  return total;
}
int getImportance(List emps, int eid) {
    Map m = new HashMap<>();
    for (Employee e : emps) m.put(e.id, e);
    int total = 0; Deque q = new ArrayDeque<>(); q.push(eid);
    while (!q.isEmpty()) {
        Employee e = m.get(q.pop());
        total += e.importance; for (int s : e.subordinates) q.push(s);
    }
    return total;
}
int getImportance(vector emps, int eid) {
    unordered_map m;
    for (auto e : emps) m[e->id] = e;
    int total = 0; stack q; q.push(eid);
    while (!q.empty()) {
        Employee* e = m[q.top()]; q.pop();
        total += e->importance; for (int s : e->subordinates) q.push(s);
    }
    return total;
}
Time: O(n) Space: O(n)