Comparable — Sort Employees by Salary
Easy
JavaComparableSortingOOP
Problem
Define a class Employee with String name and int salary that implements Comparable<Employee>, ordering by salary DESCENDING (highest first), tiebreak by name ascending. Sort the input list and return the names in order.
Example 1
Input: [(Alice, 90), (Bob, 100), (Carol, 90)]
Output: [Bob, Alice, Carol]
Constraints
- 1 ≤ list.size() ≤ 1000
Approach — Core Patterns
This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: see the walkthrough below.
Solution code
Python
class Solution:
def sortedNames(self, salaries, names):
order = sorted(range(len(names)), key=lambda i: (-salaries[i], names[i]))
return [names[i] for i in order]
Java
import java.util.*;
class Employee implements Comparable<Employee> {
String name; int salary;
Employee(String n, int s) { name = n; salary = s; }
public int compareTo(Employee o) {
if (this.salary != o.salary) return Integer.compare(o.salary, this.salary);
return this.name.compareTo(o.name);
}
}
class Solution {
public List<String> sortedNames(List<int[]> salaries, List<String> names) {
List<Employee> es = new ArrayList<>();
for (int i = 0; i < names.size(); i++) es.add(new Employee(names.get(i), salaries.get(i)[0]));
Collections.sort(es);
List<String> out = new ArrayList<>();
for (Employee e : es) out.add(e.name);
return out;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Comparable — Sort Employees by Salary interactively → ← All solutions