Neither Minimum nor Maximum - Problem
Given an integer array nums containing distinct positive integers, you need to find and return any number from the array that is neither the minimum nor the maximum value in the array.
If no such number exists (meaning the array has fewer than 3 elements), return -1.
Goal: Find any "middle" value that isn't an extreme.
Key Points:
- All integers are distinct and positive
- You can return any valid middle value
- Arrays with less than 3 elements should return -1
Input & Output
example_1.py โ Basic Case
$
Input:
[3, 2, 1, 4]
โบ
Output:
2
๐ก Note:
The minimum is 1, maximum is 4. Both 2 and 3 are neither min nor max, so we can return either (2 is found first in most approaches).
example_2.py โ Multiple Middle Values
$
Input:
[1, 2, 3, 4, 5]
โบ
Output:
2
๐ก Note:
Minimum is 1, maximum is 5. Elements 2, 3, and 4 are all valid answers. We return the first one encountered.
example_3.py โ Edge Case
$
Input:
[1, 2]
โบ
Output:
-1
๐ก Note:
Array has only 2 elements, so every element is either minimum or maximum. No middle element exists.
Constraints
- 1 โค nums.length โค 100
- 1 โค nums[i] โค 1000
- All integers in nums are distinct
- All integers are positive
Visualization
Tap to expand
Understanding the Visualization
1
Identify Extremes
First, determine who are the shortest and tallest students
2
Find Anyone In Between
Look for any student who isn't one of these extremes
3
Return First Found
As soon as you find someone in the middle, that's your answer
Key Takeaway
๐ฏ Key Insight: Since we only need ANY middle element (not a specific one), we can return immediately upon finding the first element that's neither the current minimum nor maximum!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code