Neither Minimum nor Maximum
Let’s figure out how to find a number in the given array that is neither the minimum nor the maximum value.
Approach
- Find the Minimum and Maximum Values: Identify the minimum and maximum values in the array. This can be done easily using built-in functions or by iterating through the array once.
- Search for an Intermediate Value: Look for a number that is not equal to the minimum or maximum value. If such a number is found, it’s the answer.
- Handle Edge Cases: If the array only contains two distinct numbers, there will be no such number that is neither minimum nor maximum, so we should return -1.
Code
|
|
Explanation
- The code first finds the minimum and maximum values in the array using the
min
andmax
functions. - Then it iterates through the array, checking if any number is different from both the minimum and maximum values. If such a number is found, it returns it immediately.
- If no such number is found, the function returns -1, as per the problem statement.
- Since all values in
nums
are distinct, there’s no ambiguity in defining the minimum and maximum values. - This code works even if there are only two numbers in the array, as it will return -1 in that case, satisfying the constraint and the example provided.