Department Highest Salary — LeetCode #184 (Medium)
Tags: Database
Related patterns: Hash Map, Grouping, Aggregation
Brute Force approach
Time complexity: O(n²). Space complexity: O(1).
In the brute force approach, we will check each employee's salary against all other employees in the same department to find the highest salary. This method is straightforward but inefficient.
This complexity arises because for each employee (n), we are potentially comparing their salary with every other employee in the same department (n), leading to n * n comparisons.
- Step 1: For each employee, retrieve their department ID.
- Step 2: Compare the salary of the current employee with all other employees in the same department.
- Step 3: If the current employee's salary is higher than all others in the department, store their information as the highest salary for that department.
1. For employee Joe (salary 70000, department 1), check Jim (90000) and Max (90000) — not the highest.
2. For employee Jim (salary 90000, department 1), no one has a higher salary — store Jim.
3. For employee Henry (salary 80000, department 2), check Sam (60000) — Henry is highest.
4. For employee Sam (salary 60000, department 2), not higher than Henry.
5. Result: Jim (90000, department 1) and Henry (80000, department 2).
Optimal Solution approach
Time complexity: O(n). Space complexity: O(n).
The optimal solution uses a single pass through the Employee table to find the highest salary for each department using a HashMap. This reduces the number of comparisons significantly.
This complexity is linear because we only pass through the Employee table once to build the HashMap, and then we perform a single query to get the results.
- Step 1: Initialize a HashMap to store the highest salary and corresponding employee for each department.
- Step 2: Iterate through the Employee table, updating the HashMap with the employee details if their salary is higher than the current stored salary for that department.
- Step 3: Extract the results from the HashMap to get the final output.
1. Initialize HashMap: {}.
2. Process Joe (70000, department 1) -> HashMap: {1: (Joe, 70000)}.
3. Process Jim (90000, department 1) -> HashMap: {1: (Jim, 90000)}.
4. Process Henry (80000, department 2) -> HashMap: {1: (Jim, 90000), 2: (Henry, 80000)}.
5. Process Sam (60000, department 2) -> No change in HashMap.
6. Final result: Jim (90000, department 1) and Henry (80000, department 2).
Key Insights
- Using a HashMap allows efficient storage and retrieval of maximum salaries.
- Grouping by department reduces the need for nested loops.
Common Mistakes
- Not considering employees with the same highest salary.
- Overlooking the need to join with the Department table for final output.
Interview Tips
- Always clarify if you need to handle ties in salaries.
- Discuss your thought process and approach before jumping into coding.
- Practice writing SQL queries as they are common in technical interviews.