Neither Minimum nor Maximum Solution in Java


Problem Description

So, you think you can just waltz into a room full of numbers and pick the first, second, or third one that catches your eye? Well, think again! The “Neither Minimum nor Maximum” problem is like trying to find that one friend who always stands in the middle of a group photo—neither the tallest nor the shortest, just chilling in the middle.

In this LeetCode challenge, you’re given an array of integers, and your mission, should you choose to accept it, is to find a number that is neither the minimum nor the maximum. If you have fewer than three numbers, you might as well pack your bags and go home because the answer is -1.

Imagine you’re at a party with three friends: one is a giant, one is a munchkin, and the other is just average height. You need to find the average-height friend, but if you only have the giant and the munchkin, well, good luck with that!

Code Solution


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

Approach

The approach here is as straightforward as it gets. First, we check if the array has fewer than three elements. If it does, we return -1 because, let’s face it, you can’t have a middle number with less than three. If we have enough numbers, we sort the first three elements of the array and simply return the second one. Voilà! You’ve found your average-height friend!

Time and Space Complexity

Complexity Type Complexity
Time Complexity O(1)
Space Complexity O(1)

Real-World Example

Imagine you’re at a talent show with three contestants: a singer, a dancer, and a magician. The singer is the best, the dancer is the worst, and the magician is just okay. You need to give the magician a trophy for being neither the best nor the worst. If there were only the singer and the dancer, you’d have a problem—no trophy for the magician!

Similar Problems

If you enjoyed this problem, you might want to check out these related challenges:

  • Two Sum Solution in Java