↓Skip to main content
  1. LeetCode/

LeetCode 181: Employees Earning More Than Their Managers

·1 min· ·
LeetCode Easy Database
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2021-10-09

  • Submissions: Runtime Error → Wrong Answer ×2 → Accepted → Wrong Answer → Accepted

Approach
#

One table plays both employee and manager, so self-join it (SQL Template 3): e.managerId = m.id pairs each employee with the manager, and e.salary > m.salary filters. Name the output column Employee. People without a manager have a NULL managerId, never join, and are excluded naturally.

My Attempts
#

This took 6 submissions:

  • Attempt 1 selected Name without an alias, ambiguous because both aliases have Name (RE).
  • With A.Name, the output column was not named Employee; one version switched to SELECT * to inspect the data. a.Name AS 'Employee' passed.

Solution
#

SELECT e.name AS Employee
FROM Employee e
JOIN Employee m ON e.managerId = m.id
WHERE e.salary > m.salary;

Complexity
#

A self join, near O(n) with an index.

Mistakes to Avoid
#

  • Qualify columns with an alias; a bare Name is ambiguous.
  • The output column must be named Employee.
  • Alias case does not matter in MySQL by default, but keep it consistent.

Interview Explanation
#

The table plays both roles, so I self-join it, matching each employee’s managerId to the manager’s id, keep employees earning more, and name the column Employee.

Related

LeetCode 175: Combine Two Tables
·1 min
LeetCode Easy Database
LeetCode 175 note: people without an address must still appear, so LEFT JOIN, leaving city and state NULL when unmatched
LeetCode 182: Duplicate Emails
·1 min
LeetCode Easy Database
LeetCode 182 note: group by email and keep groups with HAVING COUNT(*) > 1
LeetCode 183: Customers Who Never Order
·1 min
LeetCode Easy Database
LeetCode 183 note: LEFT JOIN Orders, and customers with no matching order (o.id IS NULL) never ordered; NOT IN also works
LeetCode 196: Delete Duplicate Emails
·2 mins
LeetCode Easy Database
LeetCode 196 note: it must be a DELETE, not a SELECT; keep only the smallest id per email and delete the rest
LeetCode 26: Remove Duplicates from Sorted Array
·2 mins
LeetCode Easy Array Two-Pointers
LeetCode 26 note: overwrite in place with a write pointer for the next slot, writing only values different from the last one written
LeetCode 14: Longest Common Prefix
·2 mins
LeetCode Easy Array String Trie
LeetCode 14 note: bound by the shortest string and check each position across all strings; the first mismatch gives the answer’s length