max() and min() in Python - Time & Space Complexity
When we use max() or min() on a list, we want to find the biggest or smallest item quickly.
We ask: How does the time to find these values grow as the list gets bigger?
Analyze the time complexity of the following code snippet.
numbers = [3, 7, 2, 9, 4]
maximum = max(numbers)
minimum = min(numbers)
print(f"Max: {maximum}, Min: {minimum}")
This code finds the largest and smallest numbers in a list.
- Primary operation: Checking each item in the list once to compare values.
- How many times: Each element is checked exactly one time for max and one time for min.
As the list gets bigger, the number of checks grows in a straight line with the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 checks (10 for max, 10 for min) |
| 100 | About 200 checks |
| 1000 | About 2000 checks |
Pattern observation: The work doubles when the list size doubles because max and min each look at every item once.
Time Complexity: O(n)
This means the time to find max and min grows directly with the size of the list.
[X] Wrong: "max() and min() find the answer instantly, no matter the list size."
[OK] Correct: They must look at every item to be sure which is biggest or smallest, so time grows with list size.
Understanding how max() and min() work helps you explain how searching through data scales, a key skill in many coding tasks.
"What if we used max() and min() on a sorted list? How would the time complexity change?"