#1731
The Number of Employees Which Report to Each Employee
EasyDatabaseHash MapArray
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)
In the optimal approach, we can use a single pass to create a mapping of managers to their reports. This reduces the number of iterations needed, making it much more efficient.
⚙️
Algorithm
4 steps- 1Step 1: Create a mapping of each employee's reports using a HashMap.
- 2Step 2: For each employee, if they have reports, calculate the count and average age using the mapping.
- 3Step 3: Store the results in a list.
- 4Step 4: Sort the results by employee_id.
solution.py23 lines
1# Full working Python code
2import math
3from collections import defaultdict
4
5def employee_report(employees):
6 report_map = defaultdict(list)
7 for emp in employees:
8 if emp['reports_to'] is not None:
9 report_map[emp['reports_to']].append(emp)
10 result = []
11 for emp in employees:
12 if emp['employee_id'] in report_map:
13 reports = report_map[emp['employee_id']]
14 reports_count = len(reports)
15 total_age = sum(r['age'] for r in reports)
16 average_age = round(total_age / reports_count)
17 result.append({
18 'employee_id': emp['employee_id'],
19 'name': emp['name'],
20 'reports_count': reports_count,
21 'average_age': average_age
22 })
23 return sorted(result, key=lambda x: x['employee_id'])ℹ
Complexity note: The time complexity is O(n) because we only iterate through the list of employees a couple of times. The space complexity is O(n) due to the additional storage for the report mapping.
- 1Understanding the structure of the data is crucial for efficient processing.
- 2Using a HashMap can significantly reduce the time complexity by allowing quick lookups.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.