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:
- Traverse the array to determine the minimum and maximum values.
- 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.