Skip to content

Custom Comparator Drills

01 · Question

Use the language's built-in sort for each task:

  1. Sort strings in descending lexicographic order, ignoring case.
  2. Sort intervals by their end value.
  3. Sort cards by value, breaking ties with clubs < hearts < spades < diamonds.
  4. Sort cards in new-deck order: hearts < clubs < diamonds < spades, then by value.

02 · Analysis

Describe the ordering key before writing syntax:

  • Transform case when comparison should ignore it.
  • Select the exact field that defines the order.
  • Use a numeric rank map for categories with a custom order.
  • Use multiple key fields to make tie-breakers explicit.

The built-in comparison sort takes O(nlogn)O(n log n) comparisons. Include any non-constant key or comparison work in the final complexity.

03 · Solution

Built-in sort patterns

1. Case-insensitive descending order

1def case_insensitive_sort(strings):
2 return sorted(strings, key=str.lower, reverse=True)

2. Sort intervals by end

1def sort_by_interval_end(intervals):
2 return sorted(intervals, key=lambda interval: interval[1])

3. Sort cards by value, then suit

1def sort_cards(deck):
2 suit_rank = {
3 "clubs": 0,
4 "hearts": 1,
5 "spades": 2,
6 "diamonds": 3,
7 }
8 return sorted(
9 deck,
10 key=lambda card: (card.value, suit_rank[card.suit]),
11 )

4. Sort cards in new-deck order

1def new_deck_order(deck):
2 suit_rank = {
3 "hearts": 0,
4 "clubs": 1,
5 "diamonds": 2,
6 "spades": 3,
7 }
8 return sorted(
9 deck,
10 key=lambda card: (suit_rank[card.suit], card.value),
11 )