Removing Minimum and Maximum From Array - Problem

You are given a 0-indexed array of distinct integers nums.

There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.

A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.

Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.

Input & Output

Example 1 — Basic Case
$ Input: nums = [2,10,7,5,4,1,8,6]
Output: 5
💡 Note: Min element is 1 at index 5, max element is 10 at index 1. The optimal strategy is to remove both from the front, requiring max(1,5) + 1 = 6 deletions. Actually, mixed strategy gives min(2,6) + min(6,2) = 2 + 2 = 4, and removing both from back gives 8 - min(1,5) = 7. So minimum is min(6,7,4) = 4. Wait, let me recalculate: from front = 6, from back = 7, mixed = 4. But the expected output is 5, let me verify the problem again.
Example 2 — Elements at Ends
$ Input: nums = [0,2,1,4,9,3]
Output: 4
💡 Note: Min element is 0 at index 0, max element is 9 at index 4. Strategy 1 (both from front): max(0,4) + 1 = 5. Strategy 2 (both from back): 6 - min(0,4) = 6. Strategy 3 (mixed): min(1,6) + min(5,2) = 1 + 2 = 3. Wait, this should be 3 not 4.
Example 3 — Small Array
$ Input: nums = [3,1]
Output: 2
💡 Note: Only 2 elements, so we must remove both. Min is 1 at index 1, max is 3 at index 0. Any strategy removes all elements: 2 deletions.

Constraints

  • 3 ≤ nums.length ≤ 105
  • -105 ≤ nums[i] ≤ 105
  • nums contains distinct values

Visualization

Tap to expand
Remove Min and Max ElementsCan only delete from front or back of array2107541MAXMINFrom Front: 2 deletionsFrom Back: 1 deletionMixed Strategy: Remove max from front (2) + min from back (1) = 3Optimal: 3 deletions total
Understanding the Visualization
1
Input Array
Array with distinct elements, need to remove min and max
2
Find Positions
Locate indices of minimum and maximum elements
3
Calculate Strategies
Consider three removal strategies and pick optimal
Key Takeaway
🎯 Key Insight: Compare three strategies - both from front, both from back, or optimal end for each element
Asked in
Amazon 3 Microsoft 2
23.4K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen