1 · Model, solve and test · 25 MIN
Sort records with a deterministic tie-breaker
Sort records with a deterministic tie-breaker
A comparator must encode the entire output order. Sort higher scores first, then IDs lexicographically when scores tie. Copy the input array before sorting because Array.sort mutates its receiver. The IDs in this exercise are unique ASCII strings, which gives a clear code-unit ordering independent of a user locale. Human-language sorting may require a configured Intl.Collator and a documented locale rather than this identifier comparator.
Decide tie behavior before invoking sort, and copy the array first.
Read the example
type Row={id:string;score:number};
function solve(input:Row[]):Row[]{return [...input].sort((a,b)=>b.score-a.score||(a.id<b.id?-1:a.id>b.id?1:0))}
console.log(JSON.stringify(solve([{"id":"b","score":5},{"id":"a","score":5},{"id":"c","score":9}])));Check the expected output
[{"id":"c","score":9},{"id":"a","score":5},{"id":"b","score":5}]Your challenge
Return a new array of {id:string,score:number} records sorted by descending score and ascending unique ASCII ID for ties. Do not mutate the input.
Solution cost: Typically O(n log n) comparisons; sort algorithm is runtime-defined. time · O(n) copied references plus sort workspace. space
Common trap
Returning only a boolean from a comparator does not provide the required negative/zero/positive ordering.
Next lesson: Apply commands through an explicit state machine →