Comparator violates transitivity
Review this Java comparator used to sort tasks by priority then by an int weight.
Tasks come from an upstream service and weights/priorities can be any 32-bit int, including large magnitudes. The team reports sporadic `IllegalArgumentException: Comparison method violates its general contract!` from `TimSort`, but only on certain shards.
What a strong answer looks like
Separate real bugs from style. Rank issues by severity, point at the root cause rather than the symptom, and suggest a concrete fix, specific and kind.
0:00 of about 25 min
Mark a line and say what kind of problem it is.0 findings
1class Task {
2 int priority; // any 32-bit int from upstream
3 int weight; // any 32-bit int from upstream
4}
5
6void schedule(List<Task> tasks) {
7 tasks.sort((a, b) -> {
8 if (a.priority != b.priority) {
9 return a.priority - b.priority; // ascending by priority
10 }
11 return b.weight - a.weight; // descending by weight
12 });
13 run(tasks);
14}
Which questions mattered is sealed until you submit. Telling you now would just be handing over the edge cases.
Run or narrate your approach, then ask the coach.