← Back to LeetCode POTD | Portfolio Home

2091. Removing Minimum and Maximum From Array

Difficulty: Medium | Published on 2026-08-30

Let's teach this one from absolute zero, same structure as before.


1. Problem in Very Simple Language

You have a list of numbers, all different from each other (no duplicates).

Somewhere in this list is the smallest number, and somewhere else is the largest number.

You want to get rid of both of these two special numbers. But you're only allowed to remove numbers in one of two ways:

Remove from the front (delete the leftmost remaining number), or Remove from the back (delete the rightmost remaining number).

Each single removal (front or back) counts as one deletion, and it also removes whatever number happens to be sitting at that end right now — even ordinary numbers you don't care about get deleted along the way if they're \"in front of\" your target.

Your goal: find the smallest total number of deletions needed so that, by the time you're done, both the minimum and the maximum values have been removed (it's fine if other numbers get removed too, as a side effect).

What's given: an array of distinct integers. What to find: the position of the smallest and largest values, and the cheapest way to clear both of them out using only front/back deletions. What to return: the minimum number of deletions.


2. Real-Life Analogy

Imagine a line of people waiting at a bus stop, standing in a single row. Two particular people in this row are \"VIPs\" you need to send away — one is the shortest person, one is the tallest person. But there's a rule: you can only ask people to leave from the front of the line or the back of the line, one at a time — you can't just pluck someone out of the middle.

If both VIPs happen to be standing near the front, you only need a few \"front\" removals. If one VIP is near the front and the other near the back, you might get away with removing a few from each end. If both VIPs are somewhere in the middle-ish area, you have to decide: is it cheaper to clear everyone from the front up through both VIPs, clear everyone from the back up through both, or clear one VIP from the front and the other from the back (leaving the middle-most untouched people alone)?


3. Important Programming Concepts I Need First

Array

Concept: A numbered list of values, positions (called \"indices\") starting at 0. Example: INLINECODE0 — position 0 holds INLINECODE1, position 5 holds INLINECODE2. Why we need it: Our whole input is an array, and positions (indices) are the key thing we're reasoning about — not the values themselves, but where they sit.

Variable

Concept: A named \"box\" that stores a single value you can use and update later. Example: INLINECODE3 stores the number INLINECODE4 in a box named INLINECODE5. Why we need it: We need to remember where the minimum value and the maximum value are located.

Loop

Concept: A way to repeat an action for each item in a list automatically. Example: \"Go through every position in the array, checking if this is a new smallest or largest value seen so far.\" Why we need it: To find the minimum and maximum values' positions, we scan through the whole array once.

If/else

Concept: Lets the program make decisions — \"if this condition is true, do this; otherwise do something else.\" Example: \"If the current number is smaller than the smallest one seen so far, update our record.\" Why we need it: Finding min/max, and later comparing our 3 possible removal strategies, both require decision-making.

Function / Method

Concept: A named, reusable block of code that performs a specific task and can be called by name. Example: INLINECODE6 is a built-in function that returns the smaller of two numbers. Why we need it: We'll use INLINECODE7 and INLINECODE8 to simplify comparing our final strategies.

Index (position) vs Value — an important distinction

Concept: The value is the actual number stored (like INLINECODE9), while the index is where it sits in the array (like position INLINECODE10). These are two completely different things, and this problem cares almost entirely about indices, not values. Why we need it: A common beginner trap in this problem is accidentally reasoning about the values of the min/max (like \"10 is big, so...\") when really only their positions in the array matter for counting deletions.

Time Complexity

We'll use this to confirm our solution is efficient enough for arrays of length up to 100,000.

4. Understand the Input

Take Example 1: CODEBLOCK0

Let's list out each position and value:

Index01234567
Value210754186
The minimum value in this array is INLINECODE11, and it sits at index 5. The maximum value in this array is INLINECODE12, and it sits at index 1. We are looking for: the fewest total front/back deletions so that both index 5's value and index 1's value get removed. Why is it important that the minimum is at index 5 (near the back-ish/middle) while the maximum is at index 1 (near the front)? Because their positions, not their actual values (INLINECODE13 and INLINECODE14), are what determines how many deletions each strategy costs.

5. Understand the Output

Output: INLINECODE15

The explanation removes INLINECODE16 elements from the front (this removes index 0 and index 1 — and index 1 is exactly where our maximum, INLINECODE17, lives!) and INLINECODE18 elements from the back (this removes indices 7, 6, 5 — and index 5 is exactly where our minimum, INLINECODE19, lives!). Total deletions: INLINECODE20. Why is this the best? Because the minimum (index 5) and maximum (index 1) are somewhat spread apart — one near the front, one more towards the back — so a mixed \"some from front, some from back\" strategy turns out cheapest, compared to clearing everything from just one side.


6. Solve the Example Manually

Let's solve Example 1 step by step, exactly as a human would think, without code.

Step 1: Find the index of the minimum and the index of the maximum.

Scanning through INLINECODE21: Smallest value found: INLINECODE22, at index INLINECODE23. Largest value found: INLINECODE24, at index INLINECODE25.

Step 2: Figure out the smaller and larger of these two indices, since it doesn't matter which one (min or max) is on the left — what matters is their positions relative to each other.

Here, the two indices are INLINECODE26 and INLINECODE27. The smaller one is INLINECODE28 (let's call it INLINECODE29), the larger one is INLINECODE30 (let's call it INLINECODE31).

Step 3: There are exactly 3 possible strategies. Let's compute the cost of each one, using INLINECODE32 (array length).

StrategyHow it worksCost formulaCalculationResult
A: Remove both from the frontDelete everything from index 0 up through INLINECODE33 (the larger index)INLINECODE34INLINECODE35INLINECODE36
B: Remove both from the backDelete everything from INLINECODE37 (the smaller index) up through the endINLINECODE38INLINECODE39INLINECODE40
C: Remove one from front, one from backDelete everything from index 0 up through INLINECODE41, PLUS everything from INLINECODE42 to the endINLINECODE43INLINECODE44INLINECODE45
Step 4: Take the minimum of these three strategy costs.

INLINECODE46 ✔️ matches the expected output!


7. Think Like a Programmer

What do I know? The positions of the minimum and maximum values. What do I need to find? The cheapest way to guarantee both get removed, using only front or back deletions. What can I try? Since we can only chip away from the two ends, and we need to reach both special positions, there are really only a few fundamentally different \"shapes\" the deletions can take: peel entirely from the front until we've passed both targets, peel entirely from the back until we've passed both targets, or peel some from the front (covering whichever target is closer to the front) and some from the back (covering whichever target is closer to the back). What happens if I try every possibility? Actually, in this problem, there genuinely are only 3 meaningful possibilities total — not an exponential explosion — because once you know the two target positions, any front/back deletion strategy that successfully removes both must fit one of these 3 shapes. So \"try every possibility\" is actually already cheap here! Can I make it faster? It's already about as fast as possible — we just need one pass to find min/max positions, then a constant amount of arithmetic. What information should I remember? Just two numbers: the index of the minimum, and the index of the maximum. What pattern do I notice? Whichever of the two indices is smaller, calling it INLINECODE47, and whichever is larger, calling it INLINECODE48, all 3 strategies can be expressed purely in terms of INLINECODE49, INLINECODE50, and the array length INLINECODE51.


8. Start With the Brute Force Solution

Interestingly, for this particular problem, the \"brute force\" and the \"optimal\" solution are almost the same thing, because the number of genuinely different strategies is fixed at 3, regardless of array size. Let's still walk through it in the spirit of \"start simple.\"

Brute force idea: Find where the min and max are. Then directly compute the cost of each of the 3 removal strategies (front-only, back-only, mixed), and return the smallest of the three.

Why it works: Any way of clearing both endpoints using only front/back deletions must end up looking like one of these 3 shapes — you can't remove both without either (a) your front-cursor passing both, (b) your back-cursor passing both, or (c) each cursor passing exactly one.

Why it's correct: There's no 4th shape — if front-cursor passes only one target and back-cursor passes zero, the other target never gets removed, which fails the requirement.

Time complexity: INLINECODE52 — one pass to find min/max positions, then constant-time arithmetic.

Space complexity: INLINECODE53 — we only store a couple of index variables.

Since actually writing \"keep swapping while it helps\" correctly is tricky and slow, let's skip straight past this shaky brute force and go directly to reasoning about structure (Section 7's insight), which is really the natural next step for this problem. (Unlike Two Sum-style problems, here the \"obvious\" brute force isn't even clearly correct without a lot of extra care — so the real lesson is: recognize the connected-components structure early.)


9. Why Is a More Naive Idea (Simulating Deletions) Not Ideal?

You might be tempted to literally simulate removing elements one at a time from either end, trying every possible combination of \"how many from front, how many from back\" and checking if both targets got removed. If you tried all combinations of front-count and back-count (from 0 up to n each), that's up to INLINECODE54 combinations to check — for INLINECODE55, that's 10 billion checks, way too slow. Realizing that there are really only 3 meaningful shapes (not INLINECODE56 shapes) is the key simplification that avoids this slowdown entirely.


11. Find the Better Approach

"Can we avoid doing unnecessary work?"

We already avoided it, by recognizing there are only 3 possible \"shapes\" of a valid solution, rather than trying every combination of front-count and back-count.

CODEBLOCK1


⭐ Key Insight

Before the insight

It might feel like there are many ways to mix front and back deletions, and we'd need to search through combinations to find the cheapest.

The problem

Searching combinations directly would be slow, and it's not obvious at first that the search space is actually tiny.

The insight

Only the positions (indices) of the minimum and maximum matter — not their values — and any valid removal strategy must take one of exactly 3 shapes: clear everything up to and including the later-positioned target from the front, clear everything from and including the earlier-positioned target from the back, or split the work — clear the front up through the earlier target, and clear the back up through the later target. Because clearing an \"earlier\" target automatically clears anything before it too (front deletions happen in order), you never need to consider more complicated mixed strategies.

After the insight

The whole problem becomes: find two indices, sort them into INLINECODE57 and INLINECODE58, and plug them into 3 simple formulas. No simulation, no combination-searching — just direct arithmetic.

13. Dry Run the Optimized Solution

Let's dry run Example 2.

CODEBLOCK2

Index01234567
Value0-41918-2-35
Step 1: Scan to find min and max positions.
inums[i]New min? (minIndex)New max? (maxIndex)
0 (start)0minIndex=0maxIndex=0
1-4-4 < 0 → minIndex=1-4 not > 0 → maxIndex=0
21919 not < -4 → minIndex=119 > 0 → maxIndex=2
311 not < -4 → minIndex=11 not > 19 → maxIndex=2
488 not < -4 → minIndex=18 not > 19 → maxIndex=2
5-2-2 not < -4 → minIndex=1-2 not > 19 → maxIndex=2
6-3-3 not < -4 → minIndex=1-3 not > 19 → maxIndex=2
755 not < -4 → minIndex=15 not > 19 → maxIndex=2
Final: INLINECODE59 (value INLINECODE60), INLINECODE61 (value INLINECODE62).

Step 2: Compute left/right.

INLINECODE63, INLINECODE64.

Step 3: Compute all three strategies. INLINECODE65.

StrategyFormulaCalculationResult
Front onlyINLINECODE66INLINECODE67INLINECODE68
Back onlyINLINECODE69INLINECODE70INLINECODE71
MixedINLINECODE72INLINECODE73INLINECODE74
Step 4: Take the minimum.

INLINECODE75 ✔️ matches the expected output!

Notice here that \"front only\" wins, because both the min and max are conveniently located very close together near the front (indices 1 and 2).


14. Optimized Code

CODEBLOCK3

CODEBLOCK4


15. Explain Optimized Code Line by Line

INLINECODE76 — get the total count of elements; we need this for the formulas involving \"distance from the end.\" INLINECODE77 — start our search assuming index 0 holds both records, since it's the only data point we have before scanning. The INLINECODE78 loop — visits each remaining index once, updating our best-so-far records whenever we find something more extreme. INLINECODE79 / INLINECODE80 — normalize our two found positions into \"whichever comes first\" and \"whichever comes second,\" since the formulas only care about relative order, not which one was technically the min vs the max. The three formula lines — directly compute the cost of each of the 3 valid strategies, using simple index arithmetic (explained in detail in Section 9). The final INLINECODE81 — picks the cheapest of the three.


16. Test With Multiple Examples

Example 1 — Normal Case

INLINECODE82 → dry-ran manually in Section 6 → Output: INLINECODE83 ✔️

Example 2 — Different Case

INLINECODE84 → dry-ran in Section 13 → Output: INLINECODE85 ✔️

Example 3 — Edge Case (single element)

INLINECODE86. Here INLINECODE87. Scanning: INLINECODE88, INLINECODE89 (the loop from INLINECODE90 to INLINECODE91 never runs, since there's nothing to compare). INLINECODE92, INLINECODE93. Front only: INLINECODE94 Back only: INLINECODE95 Mixed: INLINECODE96

INLINECODE97 ✔️ — makes perfect sense: the single element is both the min and the max, and removing it (either \"from the front\" or \"from the back,\" they're the same action here) takes exactly 1 deletion.


17. Edge Cases

Array has exactly one element → that element is simultaneously the min and max; answer is always INLINECODE98 (see Example 3 above). Minimum and maximum are right next to each other (adjacent indices) → the \"front only\" or \"back only\" strategy is often (but not always) very cheap, since both targets get cleared together quickly from whichever side is closer. Minimum is at index 0, maximum is at index INLINECODE99 (or vice versa) → removing from both ends will each need to clear the entire array in the worst arrangement, but the \"front only\" or \"back only\" strategy will cost exactly INLINECODE100 in that case, and the mixed strategy will cost just INLINECODE101 (best case!) — showing why checking all 3 strategies matters, since which one wins really depends on the arrangement. Negative numbers involved → doesn't change anything about the logic, since we're comparing values only to find positions of min/max — Java's INLINECODE102 and INLINECODE103 work correctly on negative numbers just like positive ones. Minimum and maximum happen to be the very same position — impossible here, since the problem guarantees all values are distinct, so the smallest and largest values are always two genuinely different elements (unless the array has only 1 element, where trivially min=max=that one element).


18. Time Complexity

What is time complexity? A way to describe how the amount of work grows as the input size grows, focusing on the general trend rather than exact timing — like noting that \"checking twice as many mailboxes takes roughly twice as long,\" regardless of how fast you personally check each one.

CODEBLOCK5

Why: We only ever look at each element once, to compare it against our current best-known min and max positions. After that single pass, everything else is just plain arithmetic on two numbers (INLINECODE104 and INLINECODE105) — no further looping needed at all. This is about as fast as any algorithm could possibly be for this problem, since you can't even know where the min/max are without looking at every element at least once.


19. Space Complexity

We only ever store a small, fixed number of extra variables: INLINECODE106, INLINECODE107, INLINECODE108, INLINECODE109, INLINECODE110, and the three strategy costs. None of these grow as the array grows — we never create any new arrays, lists, or other structures that scale with INLINECODE111.

So the extra space used is INLINECODE112 — constant, regardless of how large the input array is.


20. Common Mistakes Beginners Make

❌ \"I should look at the values of the min and max (like comparing INLINECODE113 and INLINECODE114) to figure out the cost.\" ✅ Only the indices (positions) of the min and max matter for counting deletions — the actual values themselves are irrelevant once we've located them.

❌ \"I only need to consider removing from the front, or removing from the back — not both together.\" ✅ There's a third essential strategy: removing some elements from the front AND some from the back, which is often the cheapest option (as seen in Example 1). Missing this case gives wrong answers.

❌ \"I need to figure out which one (min or max) is more to the left, and treat them differently based on that.\" ✅ It doesn't matter which one is the min and which is the max — only their relative positions matter. That's exactly why we compute INLINECODE115 and INLINECODE116: this normalizes away the \"which one is which\" question entirely.

❌ \"The mixed strategy cost should be INLINECODE117 or some other combination without the INLINECODE118 and using INLINECODE119.\" ✅ Be careful with off-by-one counting: removing \"through index INLINECODE120, inclusive,\" from the front costs INLINECODE121 (not just INLINECODE122), because index INLINECODE123 is the INLINECODE124-th element when counting from 1. Similarly, removing from index INLINECODE125 to the end costs INLINECODE126 elements (not INLINECODE127), since there are exactly INLINECODE128 elements from index INLINECODE129 to index INLINECODE130 inclusive.


21. How to Recognize This Pattern in Other Problems

Watch for these signal phrases:

CODEBLOCK6

Whenever a problem restricts you to only touching the two ends of a sequence, think: the number of fundamentally different strategies is often small and fixed (not exponential) — try to enumerate them directly instead of simulating.


22. Interview Thinking

CODEBLOCK7

Applied here: this is a great example of a problem where recognizing \"there are only 3 possible shapes\" immediately gives you the optimal solution — no fancy data structure needed.


23. Mini Challenge

Try these before checking the answers:

1. If the minimum is at index 3 and the maximum is at index 3 as well... wait, could that ever actually happen in this problem? Why or why not? 2. If INLINECODE131 and INLINECODE132, what are INLINECODE133 and INLINECODE134? 3. For an array of length INLINECODE135, if INLINECODE136 and INLINECODE137 (same position — hypothetically), what would each of the 3 strategy costs be? (This helps sanity-check the formulas even though INLINECODE138 can't truly happen here, since min ≠ max means they're always different indices — think about why the formulas still \"make sense\" mathematically.)


Answer to Mini Challenge

1. No — since all values in INLINECODE139 are guaranteed distinct, the minimum and maximum are always two different values, so they must live at two different indices. They can never be the exact same position. 2. INLINECODE140, INLINECODE141. 3. Front only: INLINECODE142. Back only: INLINECODE143. Mixed: INLINECODE144. (This hypothetical case shows the mixed formula \"double counts\" the shared position if INLINECODE145 equalled INLINECODE146, which is exactly why the problem's guarantee of distinct values — and therefore genuinely different indices — matters for the formula to make sense without extra adjustment.)


24. Final Revision

🧠 Problem in One Sentence

Find the fewest front/back deletions needed to remove both the array's minimum and maximum values.

🔑 Main Idea

Only the positions of the min and max matter; sort those two positions into INLINECODE147 and INLINECODE148, then the answer is the minimum of exactly 3 possible strategies: front-only, back-only, or split between both ends.

⚙️ Algorithm

1. Scan the array once to find the index of the minimum value and the index of the maximum value. 2. Set INLINECODE149 = the smaller of these two indices, INLINECODE150 = the larger. 3. Compute: front-only cost = INLINECODE151, back-only cost = INLINECODE152, mixed cost = INLINECODE153. 4. Return the smallest of these three values.

⏱️ Complexity

Time: INLINECODE154 Space: INLINECODE155

🎯 Pattern to Remember

\"Only touch the two ends\" problems often reduce to a small, fixed number of enumerable strategies based purely on key positions/indices — no need to simulate deletions one by one.

25. Beginner Quiz

1. (Understanding) Why does it not matter whether the minimum comes before the maximum in the array, or the other way around? 2. (Basic concept) What is the difference between an element's value and its index, and which one actually matters for this problem's cost calculation? 3. (Logic) Why are there only 3 possible strategies for removing both the min and max, instead of many more? 4. (Dry run) For INLINECODE156, find the min and max positions, compute INLINECODE157 and INLINECODE158, and calculate all 3 strategy costs. What's the final answer? 5. (Complexity/pattern) Why is this solution INLINECODE159 and not, say, INLINECODE160 or INLINECODE161, and what key restriction in the problem statement (about how you're allowed to remove elements) is the clue that tells you to think about \"positions from the ends\" rather than searching all subsets?