Current Top Earner in Each Department
SQL & DataAuto-graded · 15 test casesLast updated
Reduce salary history to each person's current pay per department, then choose the highest-paid person in each department, with exact tie and ordering rules.
Current Top Earner in Each Department
You are given pay records for a company. Each record is a dictionary describing one person's salary in one department. Return the best-paid person in every department, using only each person's current salary there.
Record format
Each record has these keys:
employee_id(int)employee_name(str)department_id(int)department_name(str)salary(number)effective_date(str, optional): an ISO date such as"2024-01-01". The key may be absent.
A person can belong to several departments. A person can also have several records for the same department, for example after a raise or a cut.
Task
Implement highest_paid_per_department(records). It returns one dictionary per department, each describing that department's top earner.
Rules
- Current salary. Treat each
(employee_id, department_id)pair separately. Among the records of a pair, the current one is the record with the latesteffective_date.- Dates are compared as plain strings, which works because they are ISO formatted.
- A record with no
effective_datecounts as older than every record that has one. - If several records of a pair tie for the latest date, or none of them has a date, the one that appears earliest in the input is current.
- Top earner. Within each department, consider only the current records. The top earner is the one with the highest
salary.- If salaries tie, the winner is the pair whose first record appears earliest in the input list. Where that pair's current record appears does not matter.
- Older records never take part in the comparison. A person whose pay was cut is judged on the reduced pay.
- Output. Return a list with exactly one dictionary per department, containing the keys
department_id,department_name,employee_id,employee_nameandsalary. All values come from the winner's current record. - Order. Departments appear in the order of their first appearance in the input.
- If
recordsis empty, return an empty list.
Constraints
0 <= len(records) <= 10^5- Salaries are non-negative numbers.
- Every record has all keys except possibly
effective_date. - A single
department_idis always used with a consistent department name, but group by the id.
Examples
Example 1
Input: highest_paid_per_department([{'employee_id': 1, 'employee_name': 'Ava', 'department_id': 10, 'department_name': 'Engineering', 'salary': 150000, 'effective_date': '2024-01-01'}, {'employee_id': 2, 'employee_name': 'Ben', 'department_id': 10, 'department_name': 'Engineering', 'salary': 160000, 'effective_date': '2024-01-01'}, {'employee_id': 1, 'employee_name': 'Ava', 'department_id': 20, 'department_name': 'Product', 'salary': 155000, 'effective_date': '2024-01-01'}])
Output: [{'department_id': 10, 'department_name': 'Engineering', 'employee_id': 2, 'employee_name': 'Ben', 'salary': 160000}, {'department_id': 20, 'department_name': 'Product', 'employee_id': 1, 'employee_name': 'Ava', 'salary': 155000}]
Example 2
Input: highest_paid_per_department([{'employee_id': 1, 'employee_name': 'Ava', 'department_id': 10, 'department_name': 'Engineering', 'salary': 140000, 'effective_date': '2023-01-01'}, {'employee_id': 1, 'employee_name': 'Ava', 'department_id': 10, 'department_name': 'Engineering', 'salary': 130000, 'effective_date': '2024-01-01'}, {'employee_id': 2, 'employee_name': 'Ben', 'department_id': 10, 'department_name': 'Engineering', 'salary': 135000, 'effective_date': '2024-01-01'}])
Output: [{'department_id': 10, 'department_name': 'Engineering', 'employee_id': 2, 'employee_name': 'Ben', 'salary': 135000}]
Hints
Hint 1
Handle it in two passes: first reduce each (employee_id, department_id) pair to its current record, then pick a winner per department.
Hint 2
Replace a stored record only when the new one is strictly better (strictly later date, or strictly higher salary). A dictionary keeps the insertion order of its keys, which gives the required tie-breaks and the output order.
Hint 3
Use an empty string as the date when effective_date is missing, so any real ISO date compares as later.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a "top one per group" problem with a history-cleaning step in front, so it is solved in two passes.
- Find each current record. Walk through the records and keep a dictionary keyed by
(employee_id, department_id). A record replaces the stored one only if its date is strictly greater. A missing date is treated as'', which sorts before every ISO date. - Find each department's winner. Walk through the current records and keep a dictionary keyed by
department_id. A record replaces the stored winner only if its salary is strictly greater. The winner is stored in the required output format. - Return the values of the department dictionary.
Why it is correct
- Cleaning history first matters. Taking the maximum over all records would let a person win with an old, higher salary that no longer applies.
- Keying stage 1 by the pair, not by employee alone, keeps a person's assignments in different departments independent.
- Both replacements use strict comparisons, so on a tie the earlier candidate stays. In stage 1 that is the earliest input record for the pair. In stage 2 the dictionary of current records is ordered by each pair's first appearance, because replacing a value does not move its key. So the salary tie-break goes to the pair that appeared first in the input.
- The department dictionary gets its keys in the order departments are first reached, which equals the order of their first appearance in the input. That gives the required output order.
- Empty input produces empty dictionaries and so an empty list.
Complexity
- Time: O(n), since each record and each pair is processed once.
- Space: O(p + d), where p is the number of distinct (employee, department) pairs and d is the number of departments.
Reference solution
from typing import List, Dict
def highest_paid_per_department(records: List[Dict]) -> List[Dict]:
# Stage 1: keep the current (latest-dated) record for each pair.
current = {}
for rec in records:
key = (rec['employee_id'], rec['department_id'])
date = rec.get('effective_date', '')
if key not in current or date > current[key].get('effective_date', ''):
current[key] = rec
# Stage 2: choose the highest salary per department.
best = {}
for rec in current.values():
dept = rec['department_id']
if dept not in best or rec['salary'] > best[dept]['salary']:
best[dept] = {
'department_id': rec['department_id'],
'department_name': rec['department_name'],
'employee_id': rec['employee_id'],
'employee_name': rec['employee_name'],
'salary': rec['salary'],
}
return list(best.values())