#2733

Neither Minimum nor Maximum

Easy
ArraySortingArraySorting
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal approach finds the minimum and maximum values in a single pass and then checks for a valid number in a second pass. This reduces the time complexity significantly.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize min and max values to the first element of the array.
  2. 2Step 2: Iterate through the array to find the actual minimum and maximum values.
  3. 3Step 3: Iterate through the array again to find and return any number that is neither the minimum nor the maximum.
solution.py13 lines
1# Full working Python code
2
3def neither_min_max(nums):
4    min_val = max_val = nums[0]
5    for num in nums:
6        if num < min_val:
7            min_val = num
8        if num > max_val:
9            max_val = num
10    for num in nums:
11        if num != min_val and num != max_val:
12            return num
13    return -1

Complexity note: The time complexity is O(n) because we only pass through the array a couple of times. The space complexity is O(1) as we only use a few variables.

  • 1The problem requires distinguishing between minimum and maximum values.
  • 2The array must have at least three distinct values to have a valid answer.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.