Employee Importance — LeetCode 690 Python Solution

MediumTreeDepth-First SearchBreadth-First SearchArrayHash Table
Problem
#690
Reading time
3 min

The problem

You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs. You are given an array of employees employees where: employees[i].id is the ID of the ith employee.

Example

Input
employees = [[1,5,[2,3]],[2,3,[]],[3,3,[]]], id = 1
Output
11
Explanation
Employee 1 has an importance value of 5 and has two direct subordinates: employee 2 and employee 3.

Python solution

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
"""


class Solution:
    def getImportance(self, employees: List["Employee"], id: int) -> int:
        def dfs(i: int) -> int:
            return d[i].importance + sum(dfs(j) for j in d[i].subordinates)

        d = {e.id: e for e in employees}
        return dfs(id)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 690. Employee Importance is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 690. Employee Importance?
LeetCode 690. Employee Importance is rated Medium on LeetCode.
What is the time complexity of LeetCode 690. Employee Importance?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 690. Employee Importance?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 690. Employee Importance cover?
LeetCode 690. Employee Importance is tagged Tree, Depth-First Search, Breadth-First Search, Array and Hash Table on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview