Managers with at Least 5 Direct Reports — LeetCode 570 Python Solution
MediumDatabase
- Problem
- #570
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Find the names of the managers who have at least five employees reporting directly to them. The Employee table has id (int, primary key), name (varchar), department (varchar) and managerId (int), which is null when the employee has no manager, and nobody manages themselves. Return the names in a column called name.
Example
- Input
- Employee(id, name, department, managerId) = (101, 'Nia', 'Engineering', null), (102, 'Omar', 'Engineering', 101), (103, 'Pia', 'Engineering', 101), (104, 'Raj', 'Engineering', 101), (105, 'Sam', 'Engineering', 101), (106, 'Tess', 'Engineering', 101), (107, 'Uma', 'Sales', 102)
- Output
- name = 'Nia'
- Explanation
- Ids 102 to 106 report to 101, so Nia has five direct reports; Omar has only one.
Python solution
Python
import pandas as pd
def find_managers(employee: pd.DataFrame) -> pd.DataFrame:
# Group the employees by managerId and count the number of direct reports
manager_report_count = (
employee.groupby("managerId").size().reset_index(name="directReports")
)
# Filter managers with at least five direct reports
result = manager_report_count[manager_report_count["directReports"] >= 5]
# Merge with the Employee table to get the names of these managers
result = result.merge(
employee[["id", "name"]], left_on="managerId", right_on="id", how="inner"
)
# Select only the 'name' column and drop the 'id' and 'directReports' columns
result = result[["name"]]
return resultComplexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 570. Managers with at Least 5 Direct Reports?
- LeetCode 570. Managers with at Least 5 Direct Reports is rated Medium on LeetCode.
- What topics does LeetCode 570. Managers with at Least 5 Direct Reports cover?
- LeetCode 570. Managers with at Least 5 Direct Reports is tagged Database on LeetCode.