Given an integer array nums, return a list [min, max] holding the smallest and the largest element of the array.
You must find both values using at most ceil(3n/2) - 2 comparisons, where n is the length of the array.
The array may contain duplicate values and can have both positive and negative numbers.
Function Signature
def find_min_max(nums: list[int]) -> list[int]:
Rules
-
Return exactly two integers in the order
[min, max]
. When every element is equal (including when
n = 1
), both entries are that value.
-
The comparison budget counts comparisons between array values, including comparisons against the running minimum or maximum. Loop counters and index checks do not count.
Constraints
-
1 <= nums.length <= 10^5
-
-10^9 <= nums[i] <= 10^9
Examples
Input: nums = [3,5,1,8,-2,7]
Output: [-2,8]
The smallest element is -2 and the largest is 8. With n = 6 the budget is 7 comparisons.
Input: nums = [10,10,10]
Output: [10,10]
All elements are the same, so the minimum and the maximum are both 10.
Input: nums = [-4]
Output: [-4,-4]
A single element is both the minimum and the maximum, and the budget ceil(3/2) - 2 allows zero comparisons.