← All patterns
26 / 29
Sorting & Selection

Sorting

🧹
Picture this

A steward sorts scattered invitations by time, name, and priority until every later choice becomes obvious.

When you see it

Signal words

If the prompt uses any of these, this pattern should come to mind first.

sortorderedlexicographicearliestlatestcomparegreedy

Ask yourself

  1. Would ordering expose adjacency, duplicates, or the next best choice?
  2. Is a custom comparator the core of the problem?
  3. After sorting, can you solve with one pass?

Canonical template

items.sort((a, b) => a.start - b.start || a.end - b.end);

let best = 0;
for (const item of items) {
  best = Math.max(best, score(item));
}
return best;

Common pitfalls

Assuming JavaScript sorts numbers numerically without a comparator.

Mutating input order when the caller expects it preserved.