Neither Minimum nor Maximum Solution in Python

Problem Description

Ah, the classic dilemma of life: finding that elusive number that is neither the smallest nor the largest in a list. It’s like trying to find a middle child in a family of overachievers. The problem, titled “Neither Minimum nor Maximum,” asks you to sift through a list of integers and return a number that is neither the minimum nor the maximum. If you’re lucky enough to have fewer than three numbers, you get a big fat -1 as your answer.

Imagine you’re at a party, and everyone is either a wallflower or the life of the party. You’re looking for that one person who’s just vibing in the middle, not too shy and not too loud. That’s the number you’re after!

Code Solution


class Solution:
    def findNonMinOrMax(self, nums: list[int]) -> int:
        return -1 if len(nums) < 3 else sorted(nums[:3])[1]

Approach

The approach here is as straightforward as it gets. The code checks if the length of the list is less than three. If it is, it returns -1 because, let’s face it, you can’t have a middle number with fewer than three contenders. If there are three or more numbers, it sorts the first three numbers and returns the second one, which is the middle number. Simple, right?

Time and Space Complexity

Time Complexity: O(1) - Since we are only looking at the first three elements, the time taken does not depend on the size of the input list.

Space Complexity: O(1) - We are not using any additional space that grows with the input size.

Real-World Example

Let’s say you’re at a talent show. There are three contestants: a magician who can pull a rabbit out of a hat (the maximum), a mime who can’t say a word (the minimum), and a juggler who can toss three balls in the air without dropping them (the middle). You want to give the juggler a shout-out, but if there were only the magician and the mime, you’d just be left scratching your head, wondering why you even showed up.