#181

Employees Earning More Than Their Managers

Easy
DatabaseSelf-JoinFiltering with Conditions
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)

In this approach, we will use a self-join to directly compare employees with their managers in one query. This is more efficient because we avoid the nested subquery.

⚙️

Algorithm

3 steps
  1. 1Step 1: Perform a self-join on the Employee table to link employees with their managers.
  2. 2Step 2: Filter the results where the employee's salary is greater than their manager's salary.
  3. 3Step 3: Select the employee names from the filtered results.
solution.py4 lines
1SELECT e1.name AS Employee
2FROM Employee e1
3JOIN Employee e2 ON e1.managerId = e2.id
4WHERE e1.salary > e2.salary;

Complexity note: This complexity is O(n) because we are scanning through the Employee table once to perform the join and comparison, making it much more efficient than the brute force approach.

  • 1Self-joins can simplify comparisons between related records in the same table.
  • 2Understanding how to leverage SQL joins can significantly improve query performance.

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