# The Score Sorter

> Points on the board, sorted by who earned the most.

Canonical URL: <https://datadriven.io/problems/the_score_sorter>

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list of [name, score] pairs, sort by score descending then name ascending. Return the sorted list.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **multi-key sorting with mixed directions**, a common requirement in leaderboard and ranking systems. It checks whether candidates can construct sort keys that handle descending primary and ascending secondary sorts.

---

### Break down the requirements

#### Step 1: Sort by score descending

Higher scores should appear first.

#### Step 2: Break ties by name ascending

When two players have the same score, alphabetically earlier names come first.

#### Step 3: Return the sorted list

Maintain the (name, score) tuple format.

---

### The solution

**Composite sort key with negated score**

```python
def sort_scores(players):
    sorted_players = sorted(players, key=lambda p: (-p[1], p[0]))
    return sorted_players
```

> **Time and Space Complexity**
>
> **Time:** O(n log n) for sorting.
> 
> **Space:** O(n) for the sorted output.

> **Interviewers Watch For**
>
> Do you negate the score for descending order? The `(-score, name)` tuple key is the idiomatic Python approach for mixed-direction sorting. Candidates who use `reverse=True` lose the ascending name tie-break.

> **Common Pitfall**
>
> Using `reverse=True` on the sort. This reverses both the score and name ordering, making names sort Z-to-A on ties instead of A-to-Z.

---

## Common follow-up questions

- What if scores were strings that needed custom comparison? _(Tests using `cmp_to_key` for non-standard comparisons.)_
- What if you only needed the top 10? _(Tests using `heapq.nlargest` for O(n log 10) instead of O(n log n).)_
- How would you handle this in SQL? _(Tests `ORDER BY score DESC, name ASC`.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/the_score_sorter)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.