Removing Minimum and Maximum From Array - Problem
Array Cleanup Challenge: You're given a 0-indexed array of distinct integers. Your mission is to remove both the minimum and maximum elements from the array using the fewest possible deletions.

๐Ÿ”น Deletion Rules: You can only remove elements from the front or back of the array
๐Ÿ”น Goal: Find the minimum number of deletions needed to eliminate both extremes

Think of it as trimming a line of people where you can only remove from either end, and you need to eliminate both the shortest and tallest person with minimum moves!

Input & Output

example_1.py โ€” Basic Case
$ Input: [2, 10, 7, 5, 4, 1, 8, 6]
โ€บ Output: 5
๐Ÿ’ก Note: Minimum is 1 (index 5), Maximum is 10 (index 1). Best strategy is to remove from right: 8 - 1 = 7, but mixed approach gives us min(6+3, 2+3) = 5 deletions.
example_2.py โ€” Edge Case
$ Input: [0, -4, 19, 1, 4]
โ€บ Output: 3
๐Ÿ’ก Note: Minimum is -4 (index 1), Maximum is 19 (index 2). Left-only strategy: max(1,2)+1 = 3. Right-only: 5-min(1,2) = 4. Mixed: min(2+3, 3+4) = 5. Optimal is 3.
example_3.py โ€” Small Array
$ Input: [101]
โ€บ Output: 1
๐Ÿ’ก Note: Array has only one element, which is both minimum and maximum. We need 1 deletion to remove it.

Constraints

  • 3 โ‰ค nums.length โ‰ค 105
  • -105 โ‰ค nums[i] โ‰ค 105
  • All integers in nums are distinct
  • Array is 0-indexed

Visualization

Tap to expand
MINMAXThree Removal Strategies๐Ÿ“ Strategy 1: Left OnlyRemove from left until both gone๐Ÿ“ Strategy 2: Right OnlyRemove from right until both gone๐Ÿ“ Strategy 3: MixedOne from left, one from right๐ŸŽฏ Choose Minimum Cost Strategy
Understanding the Visualization
1
Identify Targets
Find the positions of the thinnest (minimum) and thickest (maximum) books on the shelf
2
Strategy 1 - Left Side
Calculate cost of removing books from the left until both target books are gone
3
Strategy 2 - Right Side
Calculate cost of removing books from the right until both targets are eliminated
4
Strategy 3 - Mixed Approach
Remove books from left to get one target, from right to get the other target
5
Choose Optimal
Select the strategy with minimum total removals
Key Takeaway
๐ŸŽฏ Key Insight: Only three strategies exist for optimal removal - the greedy approach calculates all three costs and picks the minimum, achieving O(n) efficiency.
Asked in
Amazon 45 Microsoft 35 Google 28 Meta 22
42.8K Views
Medium Frequency
~18 min Avg. Time
1.5K 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