#185

Department Top Three Salaries

Hard
DatabaseHash MapArray
LeetCode ↗

Approaches

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

Intuition

Time O(n log n)Space O(n)

The optimal solution uses a single pass through the Employee table to group salaries by department and then selects the top three unique salaries for each department. This reduces the number of operations significantly compared to the brute-force approach.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use a subquery to group salaries by department and find the unique salaries.
  2. 2Step 2: Use the ROW_NUMBER() function to rank salaries within each department.
  3. 3Step 3: Select employees with ranks 1 to 3 for each department.
solution.py9 lines
1# Full working Python code
2WITH RankedSalaries AS (
3    SELECT name, salary, departmentId,
4           DENSE_RANK() OVER (PARTITION BY departmentId ORDER BY salary DESC) AS rank
5    FROM Employee
6)
7SELECT name, salary, departmentId
8FROM RankedSalaries
9WHERE rank <= 3;

Complexity note: The time complexity is O(n log n) due to the sorting operation required to rank the salaries. The space complexity is O(n) because we store the results of the ranking in a temporary table.

  • 1Using DENSE_RANK() allows us to handle ties in salaries effectively.
  • 2Partitioning by department helps in isolating the salary rankings.

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