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
Finding the Middle ElementMIN: 1MIDDLE: 3โœ“ Found!MIDDLE: 7MAX: 9MIDDLE: 5Algorithm InsightWe don't need to sort or find ALL middle elementsJust identify the extremes and return ANY element that's neitherFirst valid middle element found = Answer!
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!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.4K Views
Medium Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen