Neither Minimum nor Maximum
Problem
Given an integer array nums containing distinct positive integers, find and return any number that is neither the minimum nor the maximum value in the array, or -1 if there is no such number.
nums = [3,2,1,4]2def find_non_min_or_max(nums):
if len(nums) < 3:
return -1
lo, hi = min(nums), max(nums)
for x in nums:
if x != lo and x != hi:
return x
return -1
function findNonMinOrMax(nums) {
if (nums.length < 3) return -1;
const lo = Math.min(...nums), hi = Math.max(...nums);
for (const x of nums) {
if (x !== lo && x !== hi) return x;
}
return -1;
}
class Solution {
public int findNonMinOrMax(int[] nums) {
if (nums.length < 3) return -1;
int lo = nums[0], hi = nums[0];
for (int x : nums) { lo = Math.min(lo, x); hi = Math.max(hi, x); }
for (int x : nums) {
if (x != lo && x != hi) return x;
}
return -1;
}
}
int findNonMinOrMax(vector<int>& nums) {
if (nums.size() < 3) return -1;
int lo = *min_element(nums.begin(), nums.end());
int hi = *max_element(nums.begin(), nums.end());
for (int x : nums) {
if (x != lo && x != hi) return x;
}
return -1;
}
Explanation
A number qualifies when it is strictly between the smallest and largest values — it is neither the minimum nor the maximum. Because the integers are distinct, exactly one value is the min and exactly one is the max.
That means an answer can exist only when the array has at least three elements. With one or two numbers, every value is either the min or the max, so we return -1 straight away.
Once we know there are three or more, we compute lo = min(nums) and hi = max(nums) in a single pass. Then we scan the array and return the first value that equals neither boundary — any qualifying value is acceptable.
Why is a hit guaranteed for length 3 or more? Among three distinct numbers, one is the smallest, one is the largest, and the remaining one sits in the middle. That middle value is exactly what we are looking for.
Example: [3,2,1,4]. Here lo = 1 and hi = 4. Scanning left to right, 3 is neither, so we return 3 (the reference answer 2 is equally valid since any middle value works).