Neither Minimum nor Maximum — LeetCode 2733 Python Solution

EasyArraySorting
Problem
#2733
Pattern
Sorting
Reading time
2 min

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

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.

Python solution

Python
class Solution:
    def findNonMinOrMax(self, nums: List[int]) -> int:
        mi, mx = min(nums), max(nums)
        return next((x for x in nums if x != mi and x != mx), -1)

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Sorting

Spend O(n log n) once to buy an ordering that makes the rest of the problem trivial. LeetCode 2733. Neither Minimum nor Maximum is filed here because LeetCode tags it Sorting, which is the vocabulary this hub collects.

The sorting guide has the Python template for the pattern and the 401 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2733. Neither Minimum nor Maximum?
LeetCode 2733. Neither Minimum nor Maximum is rated Easy on LeetCode.
What is the time complexity of LeetCode 2733. Neither Minimum nor Maximum?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 2733. Neither Minimum nor Maximum?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 2733. Neither Minimum nor Maximum cover?
LeetCode 2733. Neither Minimum nor Maximum is tagged Array and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview