Talentd
FleetCode
Make and follow sheets.Sign in

Neither Minimum nor Maximum solution and explanation

EasyArraySorting5 min read76.8% acceptanceUpdated 9 Apr 2026
Leetcode Weekly contest 349 - Easy - Neither Minimum nor MaximumPrakhar Agrawal · 2:03 · 335 viewsWatch on YouTube
9 more videos on this problem
  1. Leetcode Weekly contest 349 - Easy - Neither Minimum nor MaximumPrakhar Agrawal · 2:03 · 335 views
  2. 2733. Neither Minimum nor Maximum (Leetcode Easy)Programming Live with Larry · 1:42 · 332 views
  3. 6470. Neither Minimum nor Maximum | Leetcode | Weekly Contest 349 | Solution Code.Optimization · 0:14 · 286 views
  4. 2733. Neither Minimum nor Maximum || Weekly Contest 349 || Leetcode || Solution ExplainCodeLuv · 4:53 · 229 views
  5. 2733. Neither Minimum nor Maximum Leetcode ProblemsPrint Code · 2:28 · 228 views
  6. 2733. Neither Minimum nor maximum (weekly contest 349)Srajan Agrawal · 2:21 · 220 views
  7. Neither Minimum nor Maximum | LeetCode 2733 | Top Placement Question | Easy Solution For BeginnersOnlycodes · 2:55 · 197 views
  8. C++ Solution - LeetCode#2733 Neither Minimum nor MaximumJoshProgramin · 3:38 · 125 views
  9. Master LeetCode 2733: Neither Minimum nor Maximum | Python Tutorial | Weekly Contest 349vanAmsen · 4:07 · 102 views
  10. 2733. Neither Minimum nor MaximummoodyCode · 12:41 · 66 views

The 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.

Example 1:

Input: nums = [3,2,1,4]
Output: 2
Explanation: In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers.

Example 2:

Input: nums = [1,2]
Output: -1
Explanation: Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer.

Example 3:

Input: nums = [2,1,3]
Output: 2
Explanation: Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. 

Constraints:

  • 1 <= nums.length <= 100
  • 1 <= nums[i] <= 100
  • All values in nums are distinct

Approach overview

Problem Overview: You receive an integer array nums. Return any value that is neither the smallest nor the largest element in the array. If no such value exists (for example when the array has fewer than three elements), return -1. The task mainly checks basic reasoning about ordering inside an array.

Approach 1: Simple Traversal (O(n) time, O(1) space)

Scan the array once to compute the global min and max. After that, iterate through the array again and return the first value that is not equal to either of those extremes. The key observation: any element strictly between the minimum and maximum satisfies the requirement. This approach only uses constant variables and two linear passes, so the complexity stays O(n) time with O(1) extra space.

An even tighter variation looks only at the first three elements. Among three numbers, one must be the minimum, one the maximum, and the remaining value is guaranteed to be neither. Compare the three values and return the middle element. Both variants rely purely on comparisons and simple iteration, which makes them ideal when you want the fastest possible solution without modifying the array.

Approach 2: Sort and Select (O(n log n) time, O(1) or O(n) space depending on sort)

Another straightforward strategy is to sort the array using a standard sorting algorithm. After sorting, the smallest element sits at index 0 and the largest at index n-1. Any element between them (for example nums[1]) is guaranteed to be neither minimum nor maximum when n ≥ 3. The implementation becomes trivial: sort the array and return the element at index 1.

The tradeoff is complexity. Sorting costs O(n log n) time, which is slower than a linear scan. Some languages also allocate additional memory during sorting, increasing space usage. However, this approach is still practical when the array is already sorted or when sorting is required for later steps in the algorithm.

Recommended for interviews: The simple traversal approach is what interviewers expect. It demonstrates that you recognize the problem only needs comparisons and not full ordering. The sorting solution works but performs unnecessary work. Showing the linear O(n) idea proves stronger algorithmic judgment and familiarity with common array manipulation patterns.

Approach 1: Simple Traversal

This approach involves finding the minimum and maximum values of the array and then traversing the array to find any number that isn't either the minimum or the maximum. If such a number is found, return it; otherwise, return -1.

def findNumber(nums):
    minimum = min(nums)
    maximum = max(nums)
    for num in nums:
        if num != minimum and num != maximum:
            return num
    return -1

# Example use case
nums = [3, 2, 1, 4]
print(findNumber(nums))
import java.util.*;

public class Solution {
    public static int findNumber(int[] nums) {
        int min = nums[0], max = nums[0];
        for (int num : nums) {
            if (num < min) min = num;
            if (num > max) max = num;
        }
        for (int num : nums) {
            if (num != min && num != max) return num;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {3, 2, 1, 4};
        System.out.println(findNumber(nums));
    }
}
#include <iostream>
#include <vector>
using namespace std;

int findNumber(vector<int>& nums) {
    int min = nums[0], max = nums[0];
    for (int num : nums) {
        if (num < min) min = num;
        if (num > max) max = num;
    }
    for (int num : nums) {
        if (num != min && num != max) return num;
    }
    return -1;
}

int main() {
    vector<int> nums = {3, 2, 1, 4};
    cout << findNumber(nums) << endl;
    return 0;
}
function findNumber(nums) {
    let min = Math.min(...nums);
    let max = Math.max(...nums);
    for (let num of nums) {
        if (num !== min && num !== max) return num;
    }
    return -1;
}

// Example use case
const nums = [3, 2, 1, 4];
console.log(findNumber(nums));
#include <stdio.h>

int findNumber(int* nums, int numsSize) {
    int min = nums[0];
    int max = nums[0];
    for (int i = 1; i < numsSize; i++) {
        if (nums[i] < min) min = nums[i];
        if (nums[i] > max) max = nums[i];
    }
    for (int i = 0; i < numsSize; i++) {
        if (nums[i] != min && nums[i] != max) return nums[i];
    }
    return -1;
}

int main() {
    int nums[] = {3, 2, 1, 4};
    int result = findNumber(nums, 4);
    printf("%d\n", result);
    return 0;
}
using System;

public class Solution {
    public static int FindNumber(int[] nums) {
        int min = nums[0], max = nums[0];
        foreach (int num in nums) {
            if (num < min) min = num;
            if (num > max) max = num;
        }
        foreach (int num in nums) {
            if (num != min && num != max) return num;
        }
        return -1;
    }

    public static void Main() {
        int[] nums = {3, 2, 1, 4};
        Console.WriteLine(FindNumber(nums));
    }
}

This Python solution takes advantage of built-in functions min and max to find extremes, then iterates to find any number that is neither.

Complexity

Time Complexity: O(n). Space Complexity: O(1).

Try this approach in the editor

Approach 2: Sort and Select

Sorting the array and selecting the second element after sorting can also help find a number that is neither the minimum nor the maximum.

def findNumber(nums):
    if len(nums) < 3:
        return -1
    nums.sort()
    return nums[1]

# Example use case
nums = [3, 2, 1, 4]
print(findNumber(nums))
import java.util.*;

public class Solution {
    public static int findNumber(int[] nums) {
        if (nums.length < 3) return -1;
        Arrays.sort(nums);
        return nums[1];
    }

    public static void main(String[] args) {
        int[] nums = {3, 2, 1, 4};
        System.out.println(findNumber(nums));
    }
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int findNumber(vector<int>& nums) {
    if (nums.size() < 3) return -1;
    sort(nums.begin(), nums.end());
    return nums[1];
}

int main() {
    vector<int> nums = {3, 2, 1, 4};
    cout << findNumber(nums) << endl;
    return 0;
}
function findNumber(nums) {
    if (nums.length < 3) return -1;
    nums.sort((a, b) => a - b);
    return nums[1];
}

// Example use case
const nums = [3, 2, 1, 4];
console.log(findNumber(nums));
#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {
    return (*(int*)a - *(int*)b);
}

int findNumber(int* nums, int numsSize) {
    if (numsSize < 3) return -1;
    qsort(nums, numsSize, sizeof(int), compare);
    return nums[1];
}

int main() {
    int nums[] = {3, 2, 1, 4};
    int result = findNumber(nums, 4);
    printf("%d\n", result);
    return 0;
}
using System;

public class Solution {
    public static int FindNumber(int[] nums) {
        if (nums.Length < 3) return -1;
        Array.Sort(nums);
        return nums[1];
    }

    public static void Main() {
        int[] nums = {3, 2, 1, 4};
        Console.WriteLine(FindNumber(nums));
    }
}

By sorting the list in Python, the intermediary value is easily accessed and returned unless the list is less than three elements.

Complexity

Time Complexity: O(n log n). Space Complexity: O(1).

Try this approach in the editor

Approach 3: Simulation

First, we find the minimum and maximum values in the array, denoted as mi and mx respectively. Then, we traverse the array and find the first number that is not equal to mi and not equal to mx, and return it.

The time complexity is O(n), where n is the length of the array. The space complexity is O(1).

func findNonMinOrMax(nums []int) int {
	mi, mx := slices.Min(nums), slices.Max(nums)
	for _, x := range nums {
		if x != mi && x != mx {
			return x
		}
	}
	return -1
}
impl Solution {
    pub fn find_non_min_or_max(nums: Vec<i32>) -> i32 {
        let mut mi = 100;
        let mut mx = 0;

        for &ele in nums.iter() {
            if ele < mi {
                mi = ele;
            }
            if ele > mx {
                mx = ele;
            }
        }

        for &ele in nums.iter() {
            if ele != mi && ele != mx {
                return ele;
            }
        }

        -1
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Simple Traversal

Time Complexity: O(n). Space Complexity: O(1).

Sort and Select

Time Complexity: O(n log n). Space Complexity: O(1).

Simulation–

Complexity analysis

ApproachTimeSpaceWhen to Use
Simple Traversal (Find Min and Max)O(n)O(1)Best general solution when you only need any non-min/non-max element
Three-Element ComparisonO(1)O(1)Fastest trick when the array has at least three elements and you only inspect the first three values
Sort and SelectO(n log n)O(1) to O(n)Useful if the array is already being sorted for another step

Frequently asked questions

Is Neither Minimum nor Maximum easy or hard?

Neither Minimum nor Maximum is classified as an Easy problem. It focuses on basic array traversal, comparisons, and recognizing that sorting the entire array is unnecessary.

How to solve Neither Minimum nor Maximum in O(n)?

Compute the minimum and maximum of the array using a single pass. Then iterate again and return the first value that is not equal to either of those extremes. Since each element is visited at most twice, the total complexity is O(n) with constant space.

What is the best approach for Neither Minimum nor Maximum?

The best approach is a simple traversal that finds the minimum and maximum values in O(n) time, then returns any element that is different from both. This uses constant extra space and avoids unnecessary sorting. Interviewers generally expect this linear scan solution.

Is Neither Minimum nor Maximum asked at Google/Amazon/Meta?

Problems of this type appear in screening rounds at large tech companies because they test basic array reasoning and edge case handling. While this exact question may not always appear, similar easy-level array logic problems are common in interviews at companies like Amazon and Google.

What data structure is used in Neither Minimum nor Maximum?

The problem primarily uses a basic array. The solution relies on comparisons to track the minimum and maximum values and does not require additional data structures beyond a few variables.

What is the time complexity of Neither Minimum nor Maximum?

The optimal solution runs in O(n) time with O(1) extra space. It scans the array to determine the minimum and maximum values and then finds an element that lies between them. A sorting-based approach would take O(n log n) time.

Neither Minimum nor Maximum Python or Java solution approach?

In both Python and Java, iterate through the array to compute the minimum and maximum values, then scan again to return an element different from both. The logic is identical across languages and runs in O(n) time with O(1) space.

Comments

Now write it yourselfClose this page and solve Neither Minimum nor Maximum in the editor, without looking.
Practise Neither Minimum nor Maximum