Problem 1376

Abstract / Summary

A manager tells employees information level by level and we calculate the total time needed for all employees to know.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1376.py

class Solution:
    def numOfMinutes(self, n: int, headID: int, manager: List[int], informTime: List[int]) -> int:
        sub = defaultdict(list)
        for i, m in enumerate(manager):
            sub[m].append(i)

        def deeper(id):
            if id not in sub:
                return 0

            slowest = 0
            for s in sub[id]:
                slowest = max(slowest, deeper(s))
            return slowest + informTime[id]

        return deeper(headID)
16 lines | 492 bytes | submitted October 2, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 61% (400k+ submissions).

Typical patterns to solve this problem:
  • Breadth First Search
  • Depth First Search
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation solves the problem of determining the total time needed for an information cascade to reach all employees in a hierarchical organization. The hierarchy is described by a manager array where each employee’s direct manager is identified, and an informTime array that specifies how long each manager takes to inform their direct reports. Starting from the head of the organization, the algorithm computes the longest path of cumulative inform times, which corresponds to the overall time required for the message to propagate to every employee.

Construction of the Subordinate Mapping

The first logical block builds a reverse adjacency list that maps each manager to the list of their direct subordinates. This transformation is essential because the original manager array provides a parent-to-child relationship only implicitly. By iterating over the manager array with enumerate, the code captures both the employee index (i) and the manager identifier (m). For each pair, the employee is appended to the manager’s list in a defaultdict(list) structure.

sub = defaultdict(list)
for i, m in enumerate(manager):
    sub[m].append(i)

This mapping enables constant-time access to any manager’s direct reports during the recursive traversal.

Recursive Depth-First Traversal

The core of the solution is the nested function deeper, which performs a depth-first search (DFS) starting from a given employee identifier. The function first checks whether the current identifier appears as a key in the subordinate mapping. If the identifier is absent, the employee has no direct reports, and the function returns 0, indicating that no additional time is needed beyond the current point.

def deeper(id):
    if id not in sub:
        return 0

When subordinates exist, the function iterates over each direct report, recursively invoking deeper to compute the time required for the subtree rooted at that subordinate. The variable slowest tracks the maximum time among all subtrees, reflecting the fact that the overall propagation time is dictated by the longest branch. After processing all children, the function adds the current manager’s informTime to the maximum child time and returns the result.

    slowest = 0
    for s in sub[id]:
        slowest = max(slowest, deeper(s))
    return slowest + informTime[id]

The final result is obtained by invoking deeper with the headID, which represents the root of the hierarchy.

return deeper(headID)

Edge Cases Handled

The algorithm gracefully handles several edge conditions without requiring explicit checks outside the main logic.

When the organization consists of a single employee who is also the head, the manager array contains -1 for the head, and the subordinate mapping will have no entry for the head. The deeper function immediately returns 0, correctly indicating that no propagation time is needed.

If an employee’s informTime is 0, the recursion still proceeds correctly because the addition of informTime[id] does not alter the accumulated time. This situation arises when a manager can inform subordinates instantaneously, and the algorithm naturally incorporates such cases.

The code also accommodates sparse hierarchies where some managers have only one direct report while others have many. The use of max ensures that the longest chain determines the final result, regardless of the branching factor at any level.

When the manager array contains -1 entries for employees other than the head (which would be invalid input), the construction of the subordinate mapping would place those employees under the key -1. Since the recursive call starts from headID, any unrelated components are never traversed, effectively isolating the valid hierarchy. This behavior demonstrates robustness against malformed but non-disruptive inputs.

Performance Optimizations

The solution leverages a few implicit optimizations that contribute to its efficiency.

The subordinate mapping is built using a defaultdict(list), which eliminates the need for explicit existence checks before appending a subordinate. This reduces overhead during the construction phase and keeps the code concise.

The recursive DFS visits each employee exactly once. By returning the computed time for each subtree and reusing that value only within the current call stack, the algorithm avoids redundant calculations. The use of a local variable slowest to retain the maximum child time ensures that only a single pass over the children is required, rather than multiple passes or auxiliary data structures.

Tail recursion is not employed, but the recursion depth is bounded by the height of the hierarchy, which in the worst case equals the number of employees. Python’s recursion limit is typically sufficient for the problem constraints, and the straightforward recursion avoids the overhead of managing an explicit stack.

The final return statement directly invokes the recursive helper with the head identifier, eliminating any unnecessary post-processing steps. This direct approach ensures that the result is produced as soon as the traversal completes.

Overall, the code combines a clear transformation of input data with a concise recursive strategy, resulting in a solution that is both readable and performant for the intended problem domain.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a big company where everyone is connected like branches on a tree. At the very top, there is one person who knows a piece of important news. That person needs to tell their team members, who then go tell their own team members, until everyone knows the news.

Think of the company as a group of friends holding hands in a line. The person at the top has a list of people they are directly in charge of. To organize this, the computer creates a map that connects every manager to the people working under them.

To figure out how long it takes for the news to reach the last person, the computer starts at the top with the person who has the news. It looks at everyone that person manages and starts a little game of follow the leader.

The computer explores each path down the branches to see how long it takes for the message to travel. If one person has many people to whisper to, the computer waits for all of them to finish their jobs. It keeps track of the time spent at each step, making sure to pick the longest path because the company cannot move faster than the person who takes the most time.

The computer keeps digging deeper and deeper through the branches until it reaches the people who are not managers themselves. Once it reaches the bottom of a branch, it adds up all the time spent passing the message along that specific path. By checking every path, the computer finds the total time needed for the message to flow from the very top to the very last leaf on the tree.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 8 | μ = 7.54 | σ = 1.31

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java
leetcode.ca C++ Java Python C# Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fartem Ruby
fsq C++
haoel C++
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
martianoff Scala
varunu28 Java
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Java
leetcode.ca C++, C#, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fartem Ruby
fsq C++
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
MacJim C++
martianoff Scala
varunu28 Java
28 links | 17 authors | 9 languages

Videos

3 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

2 similar problems

Solved On The Same Day

14 solutions   October 2, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality