Removing Minimum and Maximum From Array solution and explanation
9 more videos on this problem
Removing Minimum and Maximum From Array | LeetCode Weekly contest 269 | DSAAditya Rajiv · 16:35 · 3K views
Leetcode Weekly Contest 269, (Medium)2091. Removing Minimum and Maximum From ArrayCompetitive Somya · 7:07 · 1K views
Leetcode 2091 - Removing Minimum and Maximum from ArrayEmerald Bay · 6:26 · 1K views
2091 Removing Minimum and Maximum From Array (Leetcode Medium)Programming Live with Larry · 8:04 · 625 views
Removing Minimum and Maximum From Array |Data structure & algorithm | DSA series| Java/C++/GFGBitsByBits · 21:11 · 514 views
Leetcode Weekly Contest 269 | LEETCODE PROBLEM 2089 , 2090 , 2091 | LEETCODE | CODE EXPLAINERcode Explainer · 17:11 · 509 views
Removing Minimum and Maximum From Array - LeetCode 2091 - Python - Malayalam | Amazon InterviewWeCode Community · 22:11 · 361 views
Leetcode 2091. Removing Minimum and Maximum From Array (greedy)LetsCode · 4:45 · 350 views
Removing Minimum and Maximum From Array || Min-Max Array Trimming || Leetcode 2091DSA Solutions · 5:22 · 322 views
2091 Removing Minimum and Maximum From ArrayMath Geeks · 3:08 · 314 views
The 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.
Example 1:
Input: nums = [2,10,7,5,4,1,8,6] Output: 5 Explanation: The minimum element in the array is nums[5], which is 1. The maximum element in the array is nums[1], which is 10. We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back. This results in 2 + 3 = 5 deletions, which is the minimum number possible.
Example 2:
Input: nums = [0,-4,19,1,8,-2,-3,5] Output: 3 Explanation: The minimum element in the array is nums[1], which is -4. The maximum element in the array is nums[2], which is 19. We can remove both the minimum and maximum by removing 3 elements from the front. This results in only 3 deletions, which is the minimum number possible.
Example 3:
Input: nums = [101] Output: 1 Explanation: There is only one element in the array, which makes it both the minimum and maximum element. We can remove it with 1 deletion.
Constraints:
1 <= nums.length <= 105-105 <= nums[i] <= 105- The integers in
numsare distinct.
Approach overview
Problem Overview: You receive an integer array and must remove both the minimum and maximum values using the fewest deletions. Deletions can only occur from the front or the back of the array, so the task reduces to choosing the best sequence of prefix and/or suffix removals.
Approach 1: Calculate Minimum Deletions from Three Possible Strategies (Time: O(n), Space: O(1))
First scan the array to locate the indices of the minimum and maximum values. Once you know their positions, three deletion strategies exist: remove elements only from the front, only from the back, or from both ends. If the smaller index is left and the larger index is right, the options become right + 1 deletions from the front, n - left deletions from the back, or a mixed strategy of (left + 1) + (n - right). Compute all three and return the minimum. The approach works because the order of deletions does not matter once both indices are known. This is the most direct greedy formulation of the problem and only requires a single traversal to find the min and max positions.
Approach 2: Single Pass Minimization of Deletions (Time: O(n), Space: O(1))
This variation combines index discovery and deletion calculation into a single scan. As you iterate through the array, update the current positions of the minimum and maximum elements. After each update, compute the potential deletion counts using the same three strategies (front, back, both sides) and track the smallest value seen so far. The key idea is incremental evaluation instead of waiting until the end of the scan. The algorithm still relies on the same greedy insight: once the positions of min and max are known, the optimal removal must be one of the three boundary strategies. Since only a few integers are stored, the space usage stays constant.
Recommended for interviews: The three-strategy greedy solution is what most interviewers expect. It clearly demonstrates reasoning about boundary operations in an array and reduces the problem to a small set of deterministic cases. Explaining why only three deletion strategies exist shows strong problem decomposition skills.
Approach 1: Approach 1: Calculate Minimum Deletions from Three Possible Strategies
To solve this problem efficiently, we identify the indices of the minimum and maximum elements in the array. With these indices, we consider the following three strategies for deleting the two elements:
- Remove both from the front: The target is to delete elements from the start of the array up to the farthest of the min or max indices.
- Remove both from the back: Here, we delete from the end of the array up to the farthest of the min or max indices in reverse direction.
- Remove one from each end: This involves taking both ends into consideration by removing elements from the start to the nearest of the min or max and from the end to the nearest of the other. This often results in fewer deletions than the previous strategies in certain scenarios.
Calculate the number of deletions for each strategy and return the minimum among them.
def minimum_deletions(nums):
min_idx = nums.index(min(nums))
max_idx = nums.index(max(nums))
start, end = min(min_idx, max_idx), max(min_idx, max_idx)
return min(end + 1, len(nums) - start, start + 1 + len(nums) - end)
print(minimum_deletions([2, 10, 7, 5, 4, 1, 8, 6]))
# Output: 5import java.util.*;
public class MinMaxDeletion {
public static int minimumDeletions(int[] nums) {
int minIdx = 0, maxIdx = 0;
for (int i = 1; i < nums.length; ++i) {
if (nums[i] < nums[minIdx]) minIdx = i;
if (nums[i] > nums[maxIdx]) maxIdx = i;
}
int start = Math.min(minIdx, maxIdx);
int end = Math.max(minIdx, maxIdx);
return Math.min(Math.min(end + 1, nums.length - start), start + 1 + nums.length - end);
}
public static void main(String[] args) {
int[] nums = {2, 10, 7, 5, 4, 1, 8, 6};
System.out.println(minimumDeletions(nums)); // Output: 5
}
}#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int minimumDeletions(vector<int>& nums) {
int minIdx = min_element(nums.begin(), nums.end()) - nums.begin();
int maxIdx = max_element(nums.begin(), nums.end()) - nums.begin();
int start = min(minIdx, maxIdx);
int end = max(minIdx, maxIdx);
return min({end + 1, (int)nums.size() - start, start + 1 + (int)nums.size() - end});
}
int main() {
vector<int> nums = {2, 10, 7, 5, 4, 1, 8, 6};
cout << minimumDeletions(nums) << endl; // Output: 5
return 0;
}function minimumDeletions(nums) {
let minIdx = 0, maxIdx = 0;
for (let i = 1; i < nums.length; ++i) {
if (nums[i] < nums[minIdx]) minIdx = i;
if (nums[i] > nums[maxIdx]) maxIdx = i;
}
const start = Math.min(minIdx, maxIdx);
const end = Math.max(minIdx, maxIdx);
return Math.min(end + 1, nums.length - start, start + 1 + nums.length - end);
}
console.log(minimumDeletions([2, 10, 7, 5, 4, 1, 8, 6]));
// Output: 5#include <stdio.h>
#include <stdlib.h>
int minimumDeletions(int* nums, int numsSize) {
int minIdx = 0, maxIdx = 0;
for (int i = 1; i < numsSize; ++i) {
if (nums[i] < nums[minIdx]) minIdx = i;
if (nums[i] > nums[maxIdx]) maxIdx = i;
}
int start = fmin(minIdx, maxIdx);
int end = fmax(minIdx, maxIdx);
// Three strategies
return fmin(fmin(end + 1, numsSize - start), start + 1 + numsSize - end);
}
int main() {
int nums[] = {2, 10, 7, 5, 4, 1, 8, 6};
int size = sizeof(nums) / sizeof(nums[0]);
printf("%d\n", minimumDeletions(nums, size)); // Output: 5
return 0;
}using System;
public class Solution {
public int MinimumDeletions(int[] nums) {
int minIdx = 0, maxIdx = 0;
for (int i = 1; i < nums.Length; i++) {
if (nums[i] < nums[minIdx]) minIdx = i;
if (nums[i] > nums[maxIdx]) maxIdx = i;
}
int start = Math.Min(minIdx, maxIdx);
int end = Math.Max(minIdx, maxIdx);
return Math.Min(Math.Min(end + 1, nums.Length - start), start + 1 + nums.Length - end);
}
public static void Main() {
int[] nums = {2, 10, 7, 5, 4, 1, 8, 6};
Console.WriteLine(new Solution().MinimumDeletions(nums)); // Output: 5
}
}The Python implementation makes use of the min() and max() functions to find necessary indices. It assesses the three deletion plans, helping to determine and return the minimum deletions required.
Time Complexity: O(n), as Python's min() and max() functions each scan the array.
Space Complexity: O(1).
Approach 2: Approach 2: Single Pass Minimization of Deletions
This approach also involves determining the indices of the minimum and maximum elements but optimizes the decision-making within a single loop. As the positions of min and max are found, potential deletions are calculated on the fly by maintaining tentative strategies and updating the minimal deletions required, thus avoiding any extra passes for separate calculations.
#include <iostream>
#include <vector>
#include <limits>
#include <algorithm>
using namespace std;
int minimumDeletions(vector<int>& nums) {
int minIdx = 0, maxIdx = 0, n = nums.size();
for (int i = 1; i < n; i++) {
if (nums[i] < nums[minIdx]) minIdx = i;
if (nums[i] > nums[maxIdx]) maxIdx = i;
}
int leftRemovals = max(minIdx, maxIdx) + 1;
int rightRemovals = n - min(minIdx, maxIdx);
int crossRemovals = minIdx + 1 + n - maxIdx > maxIdx + 1 + n - minIdx ? maxIdx + 1 + n - minIdx : minIdx + 1 + n - maxIdx;
return min({leftRemovals, rightRemovals, crossRemovals});
}
int main() {
vector<int> nums = {2, 10, 7, 5, 4, 1, 8, 6};
cout << minimumDeletions(nums) << endl; // Output: 5
return 0;
}#include <stdio.h>
int minimumDeletions(int* nums, int numsSize) {
int minIdx = 0, maxIdx = 0;
int n = numsSize;
for (int i = 1; i < numsSize; ++i) {
if (nums[i] < nums[minIdx]) minIdx = i;
if (nums[i] > nums[maxIdx]) maxIdx = i;
}
int leftRemovals = (maxIdx > minIdx) ? maxIdx + 1 : minIdx + 1;
int rightRemovals = (n - minIdx > n - maxIdx) ? n - minIdx : n - maxIdx;
int mixedRemovals = (minIdx + 1) + (n - maxIdx > maxIdx ? n - maxIdx : n - minIdx);
return leftRemovals <= rightRemovals && leftRemovals <= mixedRemovals ? leftRemovals : rightRemovals <= mixedRemovals ? rightRemovals : mixedRemovals;
}
int main() {
int nums[] = {2, 10, 7, 5, 4, 1, 8, 6};
printf("%d\n", minimumDeletions(nums, 8)); // Output: 5
return 0;
}The C++ solution retains optimization by calculating minimal deletions directly within the finding loop to determine required indices, hence implementing an expedited decision-making process.
Time Complexity: O(n) — as the loop is piqued of input scanning.
Space Complexity: O(1).
Approach 3: Default Approach
function minimumDeletions(nums: number[]): number {
const n = nums.length;
if (n == 1) return 1;
let i = nums.indexOf(Math.min(...nums));
let j = nums.indexOf(Math.max(...nums));
let left = Math.min(i, j);
let right = Math.max(i, j);
// 左右 left + 1 + n - right
// 两个都是左边 left + 1 + right - left = right + 1
// 都是右边 n - right + right - left = n - left
return Math.min(left + 1 + n - right, right + 1, n - left);
}func minimumDeletions(nums []int) int {
mi, mx, n := 0, 0, len(nums)
for i, num := range nums {
if num < nums[mi] {
mi = i
}
if num > nums[mx] {
mx = i
}
}
if mi > mx {
mi, mx = mx, mi
}
return min(min(mx+1, n-mi), mi+1+n-mx)
}Complexity comparison
| Approach | Complexity |
|---|---|
| Approach 1: Calculate Minimum Deletions from Three Possible Strategies | Time Complexity: O(n), as Python's |
| Approach 2: Single Pass Minimization of Deletions | Time Complexity: O(n) — as the loop is piqued of input scanning. |
| Default Approach | – |
Complexity analysis
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Three Strategy Greedy Calculation | O(n) | O(1) | General case. Clear reasoning and easiest to explain in interviews. |
| Single Pass Minimization | O(n) | O(1) | When combining scanning and evaluation in one traversal for slightly cleaner runtime flow. |
Frequently asked questions
Is Removing Minimum and Maximum From Array easy or hard?
The problem is typically classified as Medium because the implementation is simple but the key insight involves analyzing boundary deletion strategies. Once you recognize that only three removal patterns exist—front, back, or both sides—the solution becomes straightforward.
Removing Minimum and Maximum From Array Python/Java solution
Python and Java implementations follow the same logic: scan the array to track the indices of the minimum and maximum values, normalize their order using min and max, then compute the three deletion counts. Return the smallest value. The runtime is O(n) with constant extra space.
How to solve Removing Minimum and Maximum From Array in O(n)?
Traverse the array once to find the indices of the smallest and largest elements. Let the smaller index be left and the larger index be right. Calculate three possible deletion counts: remove from the front (right + 1), remove from the back (n - left), or remove from both ends ((left + 1) + (n - right)). The minimum of these three values gives the answer in linear time.
What is the best approach for Removing Minimum and Maximum From Array?
The best approach is a greedy strategy that evaluates three deletion options after locating the indices of the minimum and maximum elements. You either delete from the front until the farther index is removed, delete from the back until the nearer index is removed, or remove elements from both sides. Computing the minimum of these three values yields the optimal answer in O(n) time and O(1) space.
Is Removing Minimum and Maximum From Array asked at Google/Amazon/Meta?
Array boundary problems and greedy deletion strategies frequently appear in interviews at companies like Amazon, Google, and Meta. Variants of this question test reasoning about indices, prefix/suffix operations, and minimizing operations under constraints. The problem is commonly used in coding practice platforms to build these skills.
What data structure is used in Removing Minimum and Maximum From Array?
The problem primarily uses a simple array and index tracking. No advanced data structures are required because the solution only needs to locate the minimum and maximum values and reason about their positions relative to the array boundaries.
What is the time complexity of Removing Minimum and Maximum From Array?
The optimal solution runs in O(n) time because the array must be scanned to find the positions of the minimum and maximum elements. After obtaining the indices, computing the three deletion strategies takes constant time. Space complexity remains O(1) since only a few integer variables are stored.
