#1789
Primary Department for 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 this approach, we will use a single pass through the employee data to create a mapping of employee IDs to their primary departments. This is efficient and avoids unnecessary checks.
⚙️
Algorithm
5 steps- 1Step 1: Initialize a dictionary to store the primary department for each employee.
- 2Step 2: Loop through the employee records.
- 3Step 3: If the primary_flag is 'Y', store the department_id in the dictionary.
- 4Step 4: If the employee has no primary department, store their only department.
- 5Step 5: Convert the dictionary to a list of results.
solution.py9 lines
1def primary_department(employees):
2 primary_depts = {}
3 for emp in employees:
4 emp_id = emp['employee_id']
5 if emp['primary_flag'] == 'Y':
6 primary_depts[emp_id] = emp['department_id']
7 elif emp_id not in primary_depts:
8 primary_depts[emp_id] = emp['department_id']
9 return [{'employee_id': emp_id, 'department_id': dept} for emp_id, dept in primary_depts.items()]ℹ
Complexity note: The time complexity is O(n) because we only loop through the employee list once. The space complexity is O(n) due to the dictionary storing the primary departments.
- 1Understanding how to differentiate between primary and non-primary departments is crucial.
- 2Using a dictionary to track primary departments can significantly reduce time complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.