Neither Minimum nor Maximum Solution in C++

Problem Description

Welcome to the world of LeetCode, where finding the “neither minimum nor maximum” is as easy as finding a needle in a haystack—if the haystack were made of numbers and the needle were a number that just wants to be average! The problem is simple: given an array of integers, you need to find a number that is neither the smallest nor the largest.

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 your target number! But wait, if there are only two people at the party, you’re out of luck—no middle ground there!

Code Solution


class Solution {
 public:
  int findNonMinOrMax(vector& nums) {
    if (nums.size() < 3)
      return -1;
    sort(nums.begin(), nums.begin() + 3);
    return nums[1];
  }
};

Approach

The approach here is straightforward:

  1. First, we check if the size of the array is less than 3. If it is, we return -1 because we need at least three numbers to find a middle one.
  2. Next, we sort the first three elements of the array. Why just three? Because we only care about the minimum, maximum, and the one in between!
  3. Finally, we return the second element of the sorted array, which is our desired number.

Time and Space Complexity

Time Complexity: O(1) for the sorting of three elements, which is effectively constant time.

Space Complexity: O(1) since we are not using any additional data structures that grow with input size.

Real-World Example

Let’s say you’re at a buffet with three dishes: a salad that’s too bland (minimum), a dessert that’s too sweet (maximum), and a perfectly seasoned pasta (neither minimum nor maximum). You want to recommend the pasta to your friends, but if there were only the salad and dessert, you’d have to tell them to just eat their feelings instead!

Similar Problems

Two Sum Solution in C++
Three Sum Solution in C++
Four Sum Solution in C++