Per-Group Top-3 Distinct Values with Tie Handling
SQL & DataAuto-graded · 17 test casesLast updated
Tests whether you can isolate the three highest distinct numeric values within each group and return all records that match those values, preserving correct sort order.
Per-Group Top-3 Distinct Values with Tie Handling
You are given a list of employee records. Each record is a dictionary with four fields:
id— unique integer identifiername— employee name stringsalary— integer compensation amountdept_id— integer department identifier
Your task is to return every employee whose salary falls within the three highest distinct salary amounts in their department.
What "three highest distinct amounts" means
Count salary levels, not headcount. If two employees in the same department earn the same amount, that counts as one salary level, not two. So the three slots are filled by the three largest unique salary figures in the group.
- If a salary level is tied by multiple employees, every one of them is included in the output.
- If a department has fewer than three distinct salary amounts, all of its employees are returned.
- The third-highest salary level is always included in full — no employee earning that amount is dropped.
Output format
Return a list of the same employee dictionaries (unchanged), sorted by:
dept_idascendingsalarydescending
When two employees share the same dept_id and salary, preserve their original order from the input list (stable sort).
Constraints
0 <= len(employees) <= 10^4- Each employee dict contains exactly the keys
id,name,salary,dept_id. 1 <= salary <= 10^9dept_idis a positive integer.- Employee
idvalues are unique. - An empty input list must return an empty list.
Examples
Example 1
Input: top_three_salaries_per_department([{'id': 1, 'name': 'Alice', 'salary': 120000, 'dept_id': 10}, {'id': 2, 'name': 'Bob', 'salary': 90000, 'dept_id': 10}, {'id': 3, 'name': 'Charlie', 'salary': 115000, 'dept_id': 20}, {'id': 4, 'name': 'David', 'salary': 130000, 'dept_id': 10}, {'id': 5, 'name': 'Eve', 'salary': 110000, 'dept_id': 20}])
Output: [{'id': 4, 'name': 'David', 'salary': 130000, 'dept_id': 10}, {'id': 1, 'name': 'Alice', 'salary': 120000, 'dept_id': 10}, {'id': 2, 'name': 'Bob', 'salary': 90000, 'dept_id': 10}, {'id': 3, 'name': 'Charlie', 'salary': 115000, 'dept_id': 20}, {'id': 5, 'name': 'Eve', 'salary': 110000, 'dept_id': 20}]
Hints
Hint 1
Start by partitioning the employee list into per-department buckets. Once you have a bucket, the problem reduces to finding the top-3 distinct values in a single list — what data structure makes deduplication trivial?
Hint 2
After collecting unique salaries for a department, sort them in descending order and slice off the first three. Store those three values in a set so membership checks stay O(1) when you scan the bucket for qualifying employees.
Hint 3
The final sort needs two keys: dept_id ascending and salary descending. A tuple key like (dept_id, -salary) handles both in one pass. Python's sort is stable, so ties in both keys automatically preserve input order.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is a grouped filter: for each department independently, decide which salary amounts qualify, then keep every employee who earns one of them.
Step 1 — Partition by department
Use a defaultdict(list) to bucket employees by dept_id. This is exactly what PARTITION BY dept_id does in a SQL window function. Each bucket is processed in isolation, so one department's salaries never affect another's.
Step 2 — Find the three qualifying salary levels
Within a bucket, build a set of salaries to deduplicate, then sort descending and slice [:3]. This mirrors DENSE_RANK() OVER (... ORDER BY salary DESC) with a WHERE rnk <= 3 filter. Deduplication is the critical step — without it, two employees tied at the top salary would consume two of the three slots, which is the behavior of ROW_NUMBER, not DENSE_RANK.
Store the slice in a set for O(1) membership tests in the next step.
Step 3 — Collect qualifying employees
Scan the bucket again and append every employee whose salary is in the qualifying set. Because the set was built from distinct values, all tied employees at each qualifying level are included.
Step 4 — Sort the result
Sort the accumulated result with the compound key (dept_id, -salary). Python's sort is stable, so employees who share both keys retain their original relative order from the input list.
Why this is correct
- Deduplication before slicing ensures a tie never consumes more than one rank slot (dense ranking semantics).
- Filtering by set membership means every employee at a qualifying salary level appears in the output — no ties are silently dropped.
- Independent processing per department makes the logic composable: adding or removing a department never changes another department's output.
- Stable sort makes the output deterministic even when
dept_idandsalaryboth match.
Edge cases
| Situation | Behavior |
|---|---|
| Empty input | Returns [] immediately — the loop body never executes |
| Department with 1 or 2 distinct salaries | All employees in that department are returned |
| All employees in a department tied | One distinct salary level qualifies; every employee is included |
| Tie exactly at the third level | Every employee at that salary is included |
| Many ties at the top (e.g. five employees all earning the max) | All five are returned; the second and third distinct levels still fill slots 2 and 3 |
Complexity
- Time: O(n log n). Grouping is O(n). Sorting distinct salaries per department is O(k log k) per department, which sums to O(n log n) across all departments. The final sort is O(n log n).
- Space: O(n) for the buckets, salary sets, and result list.
Reference solution
from typing import List, Dict
from collections import defaultdict
def top_three_salaries_per_department(employees: List[Dict]) -> List[Dict]:
# Partition employees into per-department buckets (equivalent to PARTITION BY dept_id)
dept_buckets = defaultdict(list)
for emp in employees:
dept_buckets[emp['dept_id']].append(emp)
result = []
for dept_id, emps in dept_buckets.items():
# Deduplicate salaries and take the three largest (equivalent to DENSE_RANK <= 3)
unique_salaries = sorted({emp['salary'] for emp in emps}, reverse=True)
qualifying = set(unique_salaries[:3])
# Include every employee whose salary is one of the qualifying amounts
for emp in emps:
if emp['salary'] in qualifying:
result.append(emp)
# ORDER BY dept_id ASC, salary DESC; stable sort preserves input order for ties
result.sort(key=lambda x: (x['dept_id'], -x['salary']))
return result