Skip to content
Problem 690 · LeetCode 690(opens in a new tab)

Employee Importance

MediumBreadth-first search

A company stores each employee as three fields: a unique id, an importance score (which can be negative), and subordinates, the ids of the people who report to them directly.

You get the list employees and one id. Return the importance of that employee plus the importance of everyone below them: their direct reports, the reports of those reports, and so on down.

Example 1

Input:  employees = [[8, 10, [4]], [4, 6, [7, 9]], [7, 2, [3]], [9, -1, []], [3, 5, []]], id = 4
Output: 12
Why:    4, 7, 9 and 3 give 6 + 2 − 1 + 5; manager 8 is not below 4
2 more examples and the constraints

Example 2

Input:  employees = [[6, 1, [2]], [2, -4, []]], id = 2
Output: -4
Why:    employee 2 has nobody below, so only its own score counts

Example 3

Input:  employees = [[1, -2, [2]], [2, -3, [3]], [3, -1, []]], id = 1
Output: -6
Why:    a chain 1 → 2 → 3 adds −2 − 3 − 1

Constraints

  • 1 ≤ number of employees ≤ 2,000
  • 1 ≤ each id ≤ 2,000, and ids are unique
  • −100 ≤ each importance ≤ 100
  • Each employee has at most one direct manager, and every listed report exists

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Search the list for each idO(n²)
  2. Map by id + BFSO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 2,000 employeesVerdict
Search the list for each idO(n²)
Passes here, but say why it is slow
Map by id + BFSO(n)
Best; one lookup per employee

n = number of employees.

Edge cases to test

  • The employee has no reports. Return its own importance, which may be negative.
  • Only one employee. The answer is that employee's importance.
  • A long chain. 2,000 employees each managing the next: iterate instead of recursing in Python.
  • People above the starting id. Managers above id are never reached, so they never count.
  • Negative scores. Importance can be below 0, so the total can be negative too.

Common mistakes

  • Searching the list for every id instead of building a map first.
  • Counting only direct reports and missing the levels below them.
  • Recursing in Python on a deep chain and hitting the recursion limit.

How to talk through it

  1. 1Clarify. Can importance be negative? Can someone have two managers? (Yes; no, so it is a tree.)
  2. 2Name the brute force. Follow the ids with a stack, scanning the list for each one: O(n²).
  3. 3Fix the lookup. One pass builds id → employee, so each lookup is O(1).
  4. 4Walk the tree. BFS from id, adding importance as you pop; a tree needs no visited set.
  5. 5Test out loud. Try a leaf, a negative score and a long chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?