Skip to contentKEEP THE CRAFTTHE SANCTUARY

Sorting

Expose useful order with an explicit comparison key, while choosing stability, mutation and memory deliberately. Compare full ordering with counting, selection and top-k heaps instead of treating one sort as every task.

6 practice exercises10 interview problems

Recognize it when Grouping equal values makes a later adjacent scan possible.

Checking your account…

Sorting Code Labs

Sort to Expose Order

Sorting pays O(n log n) once to expose adjacency, rank, sweep order, or duplicate groups. After ordering, a problem that required repeated global comparison can often be solved with one linear scan.

Choose a Sort Key

Encode every priority in one tuple: negative numeric fields for descending order, positive fields for ascending order, and a deterministic final tie-breaker. A key function is easier to audit than a custom comparator.

Design Composite Sort Keys

Reference
def rank_key(record):
    name, score, attempts = record
    return (-score, attempts, name)
Practice

Implement rank_key(record). record is [name, score, attempts]. Return a tuple key that sorts higher scores first, fewer attempts next, then names alphabetically.

Public tests

  • Encode all tie breakers

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Design Composite Sort Keys

def rank_key(record):
    name, score, attempts = record
    return (-score, attempts, name)

Translate Priorities into a Tuple

Call the existing key Lab once to inspect a record, then use that same function with sorted. This makes the three priorities visible before any sorting machinery runs.

Step Executed statement State Why
Unpack ivy name, score, attempts = record name='ivy', score=8, attempts=2 Each position has one ranking role.
Encode ivy return (-score, attempts, name) (-8, 2, 'ivy') Smaller negative scores represent higher original scores.
Encode ada return (-score, attempts, name) (-8, 2, 'ada') The complete key differs from ivy only in the last tie-breaker.
Encode neo return (-score, attempts, name) (-9, 4, 'neo') The primary score outranks the larger attempt count.
Sort complete keys sorted([['ivy', 8, 2], ['ada', 8, 2], ['neo', 9, 4]], key=rank_key) [['neo', 9, 4], ['ada', 8, 2], ['ivy', 8, 2]] Sorting compares the returned tuples lexicographically; the return statement alone does not sort records.
Print Output
print(rank_key(['ivy', 8, 2])) (-8, 2, 'ivy')
print(sorted([['ivy', 8, 2], ['ada', 8, 2], ['neo', 9, 4]], key=rank_key)) [['neo', 9, 4], ['ada', 8, 2], ['ivy', 8, 2]]

Stability does not repair a wrong key. Explicit tie priorities should be in the key; original tie order is retained only when the complete keys compare equal.

Respect Stability and Mutation

Python sorting is stable: equal keys retain their original relative order. sorted() returns a new list, while list.sort() mutates and returns None. Choose deliberately so an interview helper does not unexpectedly destroy caller-owned order.

Preserve Stable Record Order

Reference
def stable_group(records):
    return sorted(records, key=lambda record: record[0])
Practice

Implement stable_group(records). records contains [group, value] pairs. Return a new list sorted by group while preserving original order within equal groups.

Public tests

  • Verify stable ties without mutation

Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor

Preserve Stable Record Order

def stable_group(records):
    return sorted(records, key=lambda record: record[0])

Choose Sorting or Counting

Comparison sorting is the default for arbitrary values. Counting or buckets can reach O(n + k) when the key domain is small and known, but costs O(k) memory. A heap is preferable when only the top k items matter and k is much smaller than n.

Explain It in an Interview

Say: “I sort by this explicit tuple key, then scan adjacent items under this invariant.” State whether stability matters, whether mutation is allowed, and include the linear post-pass in the O(n log n) bound. The Python list reference(opens in a new tab) defines sort, and Car Fleet(opens in a new tab) demonstrates sorting to reveal processing order.

Python Version Note

Complexity & Invariants

Interview bounds depend on the stated representation, input model, and real Python operations.

OperationAverageWorstInterview note
Python comparison sortO(n log n)O(n log n)Can use existing runs; key extraction is once per record, with its own cost.
Counting over k keysO(n + k)O(n + k)Requires a small bounded integer domain.

Space

O(n) worst-case auxiliary storage for Python sorting; sorted also returns a new list.

Assumptions

  • Comparing long strings or expensive keys adds cost beyond unit comparisons.
  • The following key Lab explains priority encoding, not the internals or mastery of every sorting algorithm.

Invariants Worth Saying Aloud

  1. Sorted output is a permutation of the original records.
  2. Tuple keys compare the first differing priority; equal keys retain original order in Python sorting.

When To Use Or Avoid Sorting

Use It When

  • Use Python sorting as the default for arbitrary comparable keys.
  • A single O(n log n) ordering can replace repeated global scans in a sweep or grouping problem.

Choose Another Tool When

  • Use a minimum, quickselect or top-k heap when full order is unnecessary.
  • Counting or radix methods need bounded key assumptions; they are not drop-in comparison sorts.

Common Pitfalls

These are the mistakes most likely to survive a happy-path example and fail a boundary case.

Reversing all priorities together

reverse=True makes names descend as well as scores. The contract wants high score but alphabetical ties.

Prevent it: Negate only descending numeric fields and retain ascending tie fields.

Avoid

ordered = sorted(records, key=lambda r: (r[1], r[0]), reverse=True)

Use instead

ordered = sorted(records, key=lambda r: (-r[1], r[0]))

Assigning the return from list.sort

list.sort mutates the list and returns None. Assigning that result loses the list reference needed next.

Prevent it: Use sorted for a new result or call sort as a separate mutating statement.

Avoid

ordered = values.sort()

Use instead

ordered = sorted(values)

Adding an unintended tie breaker

Sorting [group,label] pairs without a key orders labels inside equal groups, destroying the requested original tie order.

Prevent it: Sort by group only when stability must retain input order inside each group.

Avoid

ordered = sorted(records)

Use instead

ordered = sorted(records, key=lambda r: r[0])

Reviewed References

Official Python documentation supports language behavior. Canonical problem pages provide additional practice context.