Neither Minimum nor Maximum - Problem

Given an integer array nums containing distinct positive integers, find and return any number from the array that is neither the minimum nor the maximum value in the array, or -1 if there is no such number.

Return the selected integer.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,2,1,4]
Output: 2
💡 Note: Array has min=1, max=4. Elements 2 and 3 are neither min nor max, so we can return either one. Return 2.
Example 2 — Small Array
$ Input: nums = [1,2]
Output: -1
💡 Note: Array has only 2 elements: min=1 and max=2. No element exists that is neither min nor max.
Example 3 — Larger Array
$ Input: nums = [2,1,3]
Output: 2
💡 Note: Array has min=1, max=3. Element 2 is neither the minimum nor maximum, so return 2.

Constraints

  • 1 ≤ nums.length ≤ 100
  • 1 ≤ nums[i] ≤ 100
  • All the numbers of nums are unique.

Visualization

Tap to expand
Neither Minimum nor Maximum INPUT nums = [3, 2, 1, 4] 3 idx 0 2 idx 1 1 idx 2 4 idx 3 Input Details Array Size: 4 Distinct positive integers ALGORITHM STEPS 1 Find Minimum Scan array: min = 1 2 Find Maximum Scan array: max = 4 3 Second Pass Find num != min and != max 4 Return Result Return found number or -1 Pass 2: Check Each Element 3 != 1 and 3 != 4 [OK] 2 != 1 and 2 != 4 [OK] 1 == min [SKIP] 4 == max [SKIP] FINAL RESULT Elements in sorted view: 1 MIN 2 OK 3 OK 4 MAX Output 2 Verification 2 is not minimum (1) 2 is not maximum (4) Key Insight: Two-Pass Solution: First pass finds min and max values. Second pass returns any element that is neither min nor max. If array has less than 3 elements, no such element exists, return -1. Time: O(n) | Space: O(1) | Simple and efficient approach for distinct positive integers. TutorialsPoint - Neither Minimum nor Maximum | Two-Pass Solution
Asked in
Google 15 Amazon 12 Microsoft 8
23.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