KatInterview

690. Employee Importance

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to calculate the total importance value of a given employee and all of their direct and indirect subordinates. The employee data forms a hierarchical structure, which can be thought of as a tree or a collection of trees (a forest). Each employee is a node, and the subordinates list defines the directed edges from a manager to their reports. The task is to find the sum of importance values for the entire subtree rooted at the employee with the given id.

Solution

Employee Importance in Python

"""
# Definition for Employee.
class Employee:
    def __init__(self, id: int, importance: int, subordinates: List[int]):
        self.id = id
        self.importance = importance
        self.subordinates = subordinates
"""
from collections import deque

class Solution:
    def getImportance(self, employees: List['Employee'], id: int) -> int:
        # Create a dictionary for O(1) lookup of employees by ID.
        emp_map = {e.id: e for e in employees}
        
        # According to constraints, the given id is always valid.
        # if id not in emp_map:
        #     return 0
        
        total_importance = 0
        # Use a deque as a queue for Breadth-First Search (BFS).
        queue = deque([id])
        
        while queue:
            # Get the current employee's ID from the left of the deque.
            current_id = queue.popleft()
            
            # Get the employee object from the map.
            current_emp = emp_map[current_id]
            
            # Add the current employee's importance to the total.
            total_importance += current_emp.importance
            
            # Add all subordinates to the right of the deque.
            for subordinate_id in current_emp.subordinates:
                queue.append(subordinate_id)
                
        return total_importance

Employee Importance in Java

/*
// Definition for Employee.
class Employee {
    public int id;
    public int importance;
    public List<Integer> subordinates;
};
*/

class Solution {
    public int getImportance(List<Employee> employees, int id) {
        // Create a map for quick access to employees by their ID.
        Map<Integer, Employee> empMap = new HashMap<>();
        for (Employee emp : employees) {
            empMap.put(emp.id, emp);
        }

        // According to constraints, id is valid. No need to check empMap.containsKey(id).

        int totalImportance = 0;
        // Use a queue for Breadth-First Search (BFS).
        Queue<Integer> queue = new LinkedList<>();
        queue.add(id);

        while (!queue.isEmpty()) {
            // Get the current employee's ID from the front of the queue.
            int currentId = queue.poll();
            
            // Get the employee object from the map.
            Employee currentEmp = empMap.get(currentId);
            
            // Add the current employee's importance to the total.
            totalImportance += currentEmp.importance;
            
            // Add all subordinates to the queue to be processed.
            for (int subordinateId : currentEmp.subordinates) {
                queue.add(subordinateId);
            }
        }
        
        return totalImportance;
    }
}

Employee Importance in C++

/*
// Definition for Employee.
class Employee {
public:
    int id;
    int importance;
    vector<int> subordinates;
};
*/

class Solution {
public:
    int getImportance(vector<Employee*> employees, int id) {
        // Create a hash map to store employee ID to Employee object mapping for quick access.
        unordered_map<int, Employee*> empMap;
        for (Employee* emp : employees) {
            empMap[emp->id] = emp;
        }

        // Check if the starting employee ID exists in the map.
        if (empMap.find(id) == empMap.end()) {
            return 0;
        }

        int totalImportance = 0;
        // Use a queue for Breadth-First Search (BFS).
        queue<int> q;
        q.push(id);

        while (!q.empty()) {
            // Get the current employee's ID from the front of the queue.
            int currentId = q.front();
            q.pop();

            // Get the employee object from the map.
            Employee* currentEmp = empMap[currentId];

            // Add the current employee's importance to the total.
            totalImportance += currentEmp->importance;

            // Add all subordinates to the queue to be processed.
            for (int subordinateId : currentEmp->subordinates) {
                q.push(subordinateId);
            }
        }

        return totalImportance;
    }
};

Employee Importance in TypeScript

/**
 * Definition for Employee.
 * class Employee {
 *     id: number
 *     importance: number
 *     subordinates: number[]
 *     constructor(id: number, importance: number, subordinates: number[]) {
 *         this.id = (id === undefined) ? 0 : id;
 *         this.importance = (importance === undefined) ? 0 : importance;
 *         this.subordinates = (subordinates === undefined) ? [] : subordinates;
 *     }
 * }
 */

function getImportance(employees: Employee[], id: number): number {
    // Create a Map for quick access to employees by their ID.
    const empMap = new Map<number, Employee>();
    for (const emp of employees) {
        empMap.set(emp.id, emp);
    }
    
    // According to constraints, the given id is always valid.
    if (!empMap.has(id)) {
        return 0; // Should not happen based on problem description.
    }

    let totalImportance = 0;
    // Use an array as a queue for Breadth-First Search (BFS).
    // Note: Using shift() on large arrays can be inefficient in JS/TS.
    // For competitive programming constraints, it's usually acceptable.
    const queue: number[] = [id];
    
    while (queue.length > 0) {
        // Get the current employee's ID from the front of the queue.
        const currentId = queue.shift()!;
        
        // Get the employee object from the map.
        const currentEmp = empMap.get(currentId)!;
        
        // Add the current employee's importance to the total.
        totalImportance += currentEmp.importance;
        
        // Add all subordinates to the queue to be processed.
        for (const subordinateId of currentEmp.subordinates) {
            queue.push(subordinateId);
        }
    }
    
    return totalImportance;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.