Maximum and minimum of an array using minimum number of comparisons

Pattern: Traversal and in-place tricks

easy

Find the minimum and maximum with about 1.5n comparisons instead of 2n, by comparing elements in pairs first.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

You are given an array of between 1 and 100,000 whole numbers. Return [smallest, largest], using as few comparisons between elements as you can. For example, for [1000, 11, 445, 1, 330, 3000] the answer is [1, 3000].

This problem is from Love Babbar's 450 sheet, and this guide has no verified link for it yet. The function name getMinMax and the return format are this guide's own. The plain version of the same task is "Find the maximum and minimum element in an array".

Think first

  • The simple method compares every element with both the minimum and the maximum. How many comparisons is that?
  • Take two new elements a and b. After comparing a with b, which one could possibly be a new minimum?
  • How do you start when the length is odd? When it is even?

Hints

    Brute force, and why it fails

    The one-pass method, with 2(n - 1) comparisons, is already O(n). This problem is about the constant: the pairing trick saves a quarter of the comparisons. Both are O(n), so outside this exercise the simpler code is usually preferred.

    The key insight

    One comparison inside each pair decides which element can only be a minimum candidate and which can only be a maximum candidate. Each element then needs comparing with just one of the two running values.

    Dry run

    10000 
    111 
    4452 
    13 
    3304 
    30005 
    smallest11
    largest1000
    comparisons1

    nums = [1000, 11, 445, 1, 330, 3000]. The length is even, so start with the first pair. One comparison says 11 is the smaller, so smallest = 11 and largest = 1000.

    Step 1 of 4

    The plan

    if n is odd:
        smallest = largest = nums[0];  i = 1
    else:
        smallest = min(nums[0], nums[1]);  largest = max(nums[0], nums[1]);  i = 2
    while i + 1 < n:
        if nums[i] < nums[i + 1]:
            smallest = min(smallest, nums[i]);  largest = max(largest, nums[i + 1])
        else:
            smallest = min(smallest, nums[i + 1]);  largest = max(largest, nums[i])
        i = i + 2
    return [smallest, largest]
    

    Complexity

    Time
    O(n)
    Space
    O(1)

    About 3n/2 - 2 comparisons for even n, against 2n - 2 for the simple pass. Both are linear.

    Edge cases

    • One element: odd length, no pairs, and the answer is that element twice.
    • Two elements: one comparison and done.
    • Odd lengths: the first element is handled alone, so every later element is in a pair.
    I've built my logic, show the code

    Java

    class Solution {
        public int[] getMinMax(int[] nums) {
            int n = nums.length;
            int smallest;
            int largest;
            int i;
            if (n % 2 == 1) {                       // odd length: the first element starts both
                smallest = nums[0];
                largest = nums[0];
                i = 1;
            } else {                                // even length: the first pair starts them
                smallest = Math.min(nums[0], nums[1]);
                largest = Math.max(nums[0], nums[1]);
                i = 2;
            }
            for (; i + 1 < n; i += 2) {
                // 1 comparison inside the pair, then 1 against min and 1 against max
                if (nums[i] < nums[i + 1]) {
                    smallest = Math.min(smallest, nums[i]);
                    largest = Math.max(largest, nums[i + 1]);
                } else {
                    smallest = Math.min(smallest, nums[i + 1]);
                    largest = Math.max(largest, nums[i]);
                }
            }
            return new int[]{smallest, largest};
        }
    }

    C++

    class Solution {
    public:
        vector<int> getMinMax(vector<int>& nums) {
            int n = static_cast<int>(nums.size());
            int smallest;
            int largest;
            int i;
            if (n % 2 == 1) {                       // odd length: the first element starts both
                smallest = nums[0];
                largest = nums[0];
                i = 1;
            } else {                                // even length: the first pair starts them
                smallest = min(nums[0], nums[1]);
                largest = max(nums[0], nums[1]);
                i = 2;
            }
            for (; i + 1 < n; i += 2) {
                // 1 comparison inside the pair, then 1 against min and 1 against max
                if (nums[i] < nums[i + 1]) {
                    smallest = min(smallest, nums[i]);
                    largest = max(largest, nums[i + 1]);
                } else {
                    smallest = min(smallest, nums[i + 1]);
                    largest = max(largest, nums[i]);
                }
            }
            return {smallest, largest};
        }
    };

    Python

    class Solution:
        def getMinMax(self, nums):
            n = len(nums)
            if n % 2 == 1:                          # odd length: the first element starts both
                smallest = largest = nums[0]
                i = 1
            else:                                   # even length: the first pair starts them
                smallest, largest = min(nums[0], nums[1]), max(nums[0], nums[1])
                i = 2
            while i + 1 < n:
                # 1 comparison inside the pair, then 1 against min and 1 against max
                if nums[i] < nums[i + 1]:
                    smallest = min(smallest, nums[i])
                    largest = max(largest, nums[i + 1])
                else:
                    smallest = min(smallest, nums[i + 1])
                    largest = max(largest, nums[i])
                i += 2
            return [smallest, largest]

    Common mistakes

    • Pairing from index 0 for odd lengths, which leaves the last element without a partner.
    • Comparing both members of a pair with both running values, which throws away the saving.
    • Looping while i < n, which reads nums[i + 1] past the end.

    Similar problems