We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Neither Minimum nor Maximum

Number: 2836

Difficulty: Easy

Paid? No

Companies: N/A


Problem Description

Given an integer array nums containing distinct positive integers, return any number that is neither the minimum nor the maximum value in the array. If no such number exists (i.e., the array has less than 3 elements), return -1.


Key Insights

  • If the length of the array is less than 3, there cannot be an element that is neither the minimum nor the maximum.
  • The problem can be solved by identifying the minimum and maximum elements and then finding any element that is not equal to either.
  • A single pass (or two passes) through the array is sufficient to determine the minimum and maximum.
  • The solution works in O(n) time with O(1) extra space.

Space and Time Complexity

Time Complexity: O(n)
Space Complexity: O(1)


Solution

The solution involves two main steps:

  1. Traverse the array to determine the minimum and maximum values.
  2. Iterate through the array a second time to find and return an element that is neither the minimum nor the maximum.
    If no such element exists (i.e., the array contains exactly two elements), return -1.

Data Structures & Algorithmic Approaches:

  • Use simple variables to store the minimum and maximum values.
  • Use a loop to check each element against these values.
  • This approach is both efficient and straightforward, leveraging simple iteration.

Code Solutions

# Define the function to find a number that is neither the minimum nor the maximum
def findMiddleElement(nums):
    # If there are less than 3 numbers, return -1
    if len(nums) < 3:
        return -1

    # Initialize the min_val and max_val with the first element
    min_val = nums[0]
    max_val = nums[0]
    
    # Find the minimum and maximum of the array
    for num in nums:
        if num < min_val:
            min_val = num
        if num > max_val:
            max_val = num

    # Iterate over the array and return the first element that is not min or max
    for num in nums:
        if num != min_val and num != max_val:
            return num

    # If no such element exists, return -1
    return -1

# Example usage:
nums = [3, 2, 1, 4]
print(findMiddleElement(nums))  # Expected output: 2 (or any valid middle element)
← Back to All Questions