Python/Algorithms for interviews 8 min
Sorting tricks
Custom keys, multi-level sorts and top-K.
sortedkeyheapq
sorted returns a new list and .sort() sorts in place. The key function decides what is compared — that is where all the power is.
python · editable
loading editor…
Try it: Sort by revenue (price times units), highest first.
Python's sort is stable, so sorting twice applies a secondary then a primary key — or use a tuple key, negating numbers to flip direction.
When you only need the largest few, heapq beats a full sort at scale.
python · editable
loading editor…
practice this