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

  1. 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.
  2. 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.
  3. 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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def findNonMinOrMax(self, nums: List[int]) -> int:
        # Find the minimum and maximum values in the array
        min_val = min(nums)
        max_val = max(nums)

        # Iterate through the array
        for num in nums:
            # If the number is neither minimum nor maximum, return it
            if num != min_val and num != max_val:
                return num

        # If there is no such number, return -1
        return -1

Explanation

  • The code first finds the minimum and maximum values in the array using the min and max 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.