Skip to main content

Solving, Not Sorting: When to Use Python’s sorted() and When to Drop Down

A timed problem-solver's guide to efficient sorting in Python


🌐 Intro

This isn’t a sorting tutorial.

It’s a guide for people solving Leetcode problems under time pressure. You don’t need to master sorting algorithms. You need to solve problems fast.

And in Python, that usually means: use ******************sorted()**************** until you can’t**.


✅ Use sorted() by Default

Python’s sorted() is fast to write, easy to read, and powerful enough for most competitive-style problems.

It handles:

  • Basic sorting
  • Reversing
  • Multi-criteria sorting (e.g., score descending, name ascending)

👁️ Understanding Multi-Criteria Sorts

This line:

sorted(data, key=lambda x: (-x.score, x.name))

Is equivalent to this in JavaScript:

data.sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));

And it also mirrors SQL's ordering logic:

ORDER BY score DESC, name ASC

Python uses tuples to represent multi-level sort logic: sort by the first value, then the second, and so on.

Example: Sorting Employees by Score, Department, and Name

Details
# Sample data: list of dictionaries representing employees
employees = [
{"name": "Alice", "department": "Sales", "score": 90},
{"name": "Bob", "department": "Engineering", "score": 95},
{"name": "Charlie", "department": "Engineering", "score": 95},
{"name": "Diana", "department": "Sales", "score": 85},
{"name": "Eve", "department": "Engineering", "score": 90},
{"name": "Frank", "department": "HR", "score": 85},
{"name": "Grace", "department": "HR", "score": 85},
]

# Sort employees by:
# 1. Score (descending)
# 2. Department (ascending)
# 3. Name (ascending)
sorted_employees = sorted(
employees, key=lambda emp: (-emp["score"], emp["department"], emp["name"])
)

# Print the sorted list
for emp in sorted_employees:
print(f"{emp['name']:7} | {emp['department']:11} | Score: {emp['score']}")

Example: Top-3 Frequency Letters

Details

This example is more like what you'd see in a Leetcode problem. At first glance, the solution look more intimidating than the employee sort — but it's actually simpler: it only involves two sort conditions instead of three. The tricky-looking part is mostly syntax.

What’s happening here is that Counter (from collections) is a subclass of dict, so when we call .items(), we get a list of (char, count) tuples. Each x in the lambda represents one of those pairs, where:

  • x[0] is the character
  • x[1] is the count

We then sort by count (descending) and break ties alphabetically by character.

from collections import Counter

s = "aabbbccde"
counter = Counter(s)

# Sort by frequency descending, then alphabetically
sorted_chars = sorted(counter.items(), key=lambda x: (-x[1], x[0]))

for char, count in sorted_chars:
print(f"{char} {count}")

Output:

b 3
a 2
c 2

We could just as well do the cast to list of tuples before passing to sorted

list_of_tuples = counter.items()
sorted_chars = sorted(list_of_tuples, key=lambda x: (-x[1], x[0]))

⚠️ When sorted() Isn't Enough

Use sorted() unless:

  • ❌ You need context-aware comparison (e.g., compare to running max/min)
  • ❌ You’re inserting into a live, sorted list (stream-style)
  • ❌ You need to minimize sort time and only care about top-N (use heapq)
  • ❌ You can’t express the rule via a static key (e.g., depends on more than one object)

🛠️ Manual Alternatives

  • heapq (priority queues / top-N selection)
  • Manual insertion sort (for online problems)
  • functools.cmp_to_key (rarely needed but available)

⚖️ Decision Tree: Use sorted() Unless...

Is the full dataset available? → No → Manual / Heap
↓ Yes
Can sorting be expressed as a key? → Yes → Use sorted()
↓ No
Needs context/global state → Manual comparator / Insertion


🔧 Use the Right Tool

This isn’t about learning sorting. This is about shipping an answer in under 20 minutes.

Use sorted() as your first choice. Drop down only when you have to.

And always solve the problem, not the sort.