Leetcode 690. Employee Importance
You are given a data structure of employee information, which includes the employee’s unique id, their importance value, and their direct subordinates’ ids.
You are asked to implement a function that takes two arguments, a list of employees
and an integer id
. The list of employees
contains Employee objects. Each Employee
object has the following attributes:
int id
int importance
vector<int> subordinates
The goal of the function is to return the total importance value of the employee with the given id, along with all their subordinates’ importance values.
Here is how the Employee
class is defined:
class Employee {
public:
int id;
int importance;
vector<int> subordinates;
};
employees
list be empty?(Assuming positive answers for clarification 1 and 2, and handling the edge case for 3.)
To solve this problem, we will use a Depth-First Search (DFS) approach. Here’s the step-by-step strategy:
id
.#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
class Employee {
public:
int id;
int importance;
vector<int> subordinates;
};
class Solution {
public:
int getImportance(vector<Employee*> employees, int id) {
// Create a map for quick lookup of employee by id
unordered_map<int, Employee*> employeeMap;
for (auto employee : employees) {
employeeMap[employee->id] = employee;
}
// DFS function to calculate total importance
function<int(int)> dfs = [&](int employeeId) -> int {
Employee* employee = employeeMap[employeeId];
int totalImportance = employee->importance;
for (int subId : employee->subordinates) {
totalImportance += dfs(subId);
}
return totalImportance;
};
// Start DFS from the given employee id
return dfs(id);
}
};
This ensures that the solution is efficient and scales well with the size of the input.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?