Python's built-in sorted() is O(n log n) and accepts a key function that tells it what to compare. Learning to express an ordering as a key is the fastest way to solve most "sort by ..." problems.
You are given a list people where each element is a two-item list [name, age]. Return a new list sorted by age ascending. If two people have the same age, order them by name alphabetically. Do not modify the input list.
Examples
Input: people = [["Bob", 30], ["Alice", 25], ["Carol", 30]]
Output: [["Alice", 25], ["Bob", 30], ["Carol", 30]]
Explanation: Alice is youngest. Bob and Carol are both 30, so they are ordered by name.
Input: people = [["Zed", 5], ["Amy", 5], ["Bo", 5]]
Output: [["Amy", 5], ["Bo", 5], ["Zed", 5]]
Constraints
0 <= len(people) <= 1000- Names are non-empty strings; ages are non-negative integers.
- Aim for O(n log n) using the built-in sort.
Goals
- Use sorted() with a key function instead of writing your own comparison loop
- Build a tuple key so that ties on one field are broken by another field
- Return a new sorted list without mutating the input