#570
Managers with at Least 5 Direct Reports
MediumDatabaseHash MapAggregationJoin
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
We can leverage SQL's aggregation functions to efficiently count the number of direct reports for each manager in one go, reducing the need for nested queries.
⚙️
Algorithm
3 steps- 1Step 1: Use GROUP BY on managerId to count the number of employees reporting to each manager.
- 2Step 2: Filter the results to only include managers with a count of 5 or more.
- 3Step 3: Join this result with the Employee table to get the names of those managers.
solution.py2 lines
1# Full working Python code
2SELECT e.name FROM Employee e JOIN (SELECT managerId FROM Employee GROUP BY managerId HAVING COUNT(*) >= 5) m ON e.id = m.managerId;ℹ
Complexity note: This complexity is linear because we are only scanning through the Employee table a couple of times, once for counting and once for joining.
- 1Using aggregation functions can greatly simplify counting tasks.
- 2Joining tables can help retrieve related information efficiently.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.