AlgoMaster Logo

Employee Importance

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Depth-First Search (DFS) Recursion

Intuition:

The main idea is to recursively calculate the total importance by summing up the importance of the given employee and recursively adding the importance of all subordinates. We will use a hashmap to quickly access an employee using their id.

Approach:

  1. Use a hashmap to store the employee id and the related Employee object for quick retrieval.
  2. Write a recursive helper function dfs that takes the id of the employee whose total importance is to be calculated.
  3. The dfs function will retrieve the employee using the hashmap, start the sum with the employee's importance, and recursively add the importance of all subordinates by calling dfs for each subordinate id.
  4. Call the dfs function starting with the given employee id.

Code:

2. Breadth-First Search (BFS)

Intuition:

Instead of using recursion, we can implement an iterative version using a queue, which will help us traverse through the employees in a level-order approach (breadth-first search).

Approach:

  1. Similar to DFS, use a hashmap to store employees by their id for quick access.
  2. Use a queue to help in the BFS approach, starting by adding the main employee id to the queue.
  3. While the queue is not empty, get the next id, add its importance, and add all its subordinates to the queue.
  4. Continue summing up the importance until the queue is empty and return the total importance.

Code: