#184

Department Highest Salary

Medium
DatabaseHash MapGroupingAggregation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space 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.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize a HashMap to store the highest salary and corresponding employee for each department.
  2. 2Step 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.
  3. 3Step 3: Extract the results from the HashMap to get the final output.
solution.py7 lines
1SELECT departmentId AS Department, name AS Employee, salary AS Salary
2FROM Employee
3WHERE (departmentId, salary) IN (
4    SELECT departmentId, MAX(salary)
5    FROM Employee
6    GROUP BY departmentId
7);

Complexity note: 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.

  • 1Using a HashMap allows efficient storage and retrieval of maximum salaries.
  • 2Grouping by department reduces the need for nested loops.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.