Start learning free

LESSON 261 OF 673 · TUPLES, SORTING & BUILT-INS

Min and Max in One Loop in Python

Practice Read the full explanation

You get a list of integers nums. Return its smallest and its largest number together, as a pair.

The smallest number comes first. The function's return type shows how your language holds the pair.

Find both in one loop. Don't use a built-in min or max function.

 

Example 1:

Input: nums = [4, -2, 9, 0]
Output: (-2, 9)
Explanation: The smallest number is -2.
The largest number is 9.

Example 2:

Input: nums = [7]
Output: (7, 7)
Explanation: The only number is both the smallest and the largest.

Example 3:

Input: nums = [-5, -1, -8]
Output: (-8, -1)
Explanation: All the numbers are below 0.
The smallest is -8, and the largest is -1.

 

Constraints:

  • nums has at least one number.
  • Every number is between -106 and 106.
STEP 1 OF 5
    Ctrl + Enter to check

    PYTHON · TUPLES, SORTING & BUILT-INS

    Min And Max in Python, explained

    Problem overview

    The method minAndMax gets a list of integers, nums, with at least one number, and returns the smallest and the largest as a pair, smallest first. In Python the pair is a tuple. For [4, -2, 9, 0] the answer is (-2, 9). For a single number, [7], both parts are that number: (7, 7). The statement asks for one loop and no built-in min or max.

    Approach

    Keep two variables, low and high, that always hold the smallest and the largest number seen so far. Look at each number once and update whichever variable it beats. After the last number, they hold the answer.

    Both start at nums[0], not at 0. If every number is above 0, a start of 0 for low would never be beaten and would be wrong. The first number is always a real candidate, and the list can't be empty.

    Step by step

    1. Set low and high to nums[0].
    2. Loop over nums with num.
    3. If num is smaller than low, replace low.
    4. If num is larger than high, replace high. This is a second if, not an elif, so both checks run on every number.
    5. After the loop, return low, high. Python packs the two values into a tuple.

    The solution in Python

    class Solution:
        def minAndMax(self, nums: List[int]) -> Tuple[int, int]:
            low = nums[0]
            high = nums[0]
            for num in nums:
                if num < low:
                    low = num
                if num > high:
                    high = num
            return low, high
    

    The loop starts with nums[0] itself, which changes nothing, so it does one harmless extra check. Because the comparisons are strict, a number equal to low or high leaves it as it is, which is fine: the value is the same either way.

    Tracing the first example

    For [4, -2, 9, 0], these are the values of num, low and high at the end of each pass:

    numlowhigh
    444
    -2-24
    9-29
    0-29

    The last number, 0, is neither a new smallest nor a new largest, so nothing changes. The function returns (-2, 9).

    Why a tuple

    The function has two results, and a function returns one object. return low, high packs both into one tuple, and the caller can unpack it: smallest, largest = Solution().minAndMax(nums). The type hint Tuple[int, int] says the same thing: two integers, in that order.

    Testing

    [4, -2, 9, 0]  ->  (-2, 9)
    [7]            ->  (7, 7)
    [-5, -1, -8]   ->  (-8, -1)
    

    The last list has only negative numbers: with low and high started at 0, high would wrongly stay 0.

    Another way, once built-ins are allowed

    Python can do the same with two calls, (min(nums), max(nums)), which gives (-2, 9) for the first example. It reads shortly but walks the list twice, while the loop above walks it once. The exercise asks for the loop so you see how min and max work inside: a variable that remembers the best value so far.

    Edge cases

    A one-number list needs no special code: low and high both start as that number and nothing beats it, so the result is (7, 7). Negative numbers and zero need no special code either, because the start values come from the list itself. The limits of the numbers (between -1,000,000 and 1,000,000) don't matter in Python, where integers don't overflow. The list is never empty, so nums[0] is always safe.

    Common mistakes

    • Starting both variables at 0, which fails for lists of only positive or only negative numbers.
    • Writing elif for the second check. It works for most lists, but two separate checks say plainly that each number is compared with both.
    • Returning high, low. The statement wants the smallest first.
    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free