Two-Pass Stable Sort Trick

Hard ⏱ 18 min 28% acceptance ★★★★★ 4.6
Python's sort is stable: equal keys keep their relative order. Exploit this to sort orders by city ascending AND amount descending using two successive <code>.sort()</code> calls with lambdas (sort by the secondary key first, primary key second) — no compound key tuples allowed.

Examples

Example 1
Input
orders = [('Pune', 200), ('Agra', 300), ('Pune', 900)]; two_pass(orders)
Output
[('Agra', 300), ('Pune', 900), ('Pune', 200)]
Explanation

Within Pune, 900 precedes 200 because the amount-descending pass ran first and stability preserved it.

Constraints

  • Exactly two .sort() calls.
  • No key tuples combining both fields.

Topics

Lambda & Functionalstable sort

Companies

GoogleAmazonMorgan Stanley

Hints

Hint 1

Sort by amount descending FIRST, then by city ascending.

Hint 2

The second sort will not disturb equal-city groups.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.