0
0
Pythonprogramming~5 mins

max() and min() in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: max() and min()
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • 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.
How Execution Grows With Input

As the list gets bigger, the number of checks grows in a straight line with the list size.

Input Size (n)Approx. Operations
10About 20 checks (10 for max, 10 for min)
100About 200 checks
1000About 2000 checks

Pattern observation: The work doubles when the list size doubles because max and min each look at every item once.

Final Time Complexity

Time Complexity: O(n)

This means the time to find max and min grows directly with the size of the list.

Common Mistake

[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.

Interview Connect

Understanding how max() and min() work helps you explain how searching through data scales, a key skill in many coding tasks.

Self-Check

"What if we used max() and min() on a sorted list? How would the time complexity change?"