Removing Minimum and Maximum From Array — LeetCode 2091 Python Solution

MediumGreedyArray
Problem
#2091
Pattern
Greedy
Reading time
2 min

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.

Example

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.

Python solution

Python
class Solution:
    def minimumDeletions(self, nums: List[int]) -> int:
        mi = mx = 0
        for i, num in enumerate(nums):
            if num < nums[mi]:
                mi = i
            if num > nums[mx]:
                mx = i
        if mi > mx:
            mi, mx = mx, mi
        return min(mx + 1, len(nums) - mi, mi + 1 + len(nums) - mx)

Complexity

MeasureComplexity
TimeO(n log n)
SpaceO(1) to O(n) auxiliary

Pattern: Greedy

Take the locally best option every time — when you can prove that never costs you later. LeetCode 2091. Removing Minimum and Maximum From Array is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.

The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2091. Removing Minimum and Maximum From Array?
LeetCode 2091. Removing Minimum and Maximum From Array is rated Medium on LeetCode.
What topics does LeetCode 2091. Removing Minimum and Maximum From Array cover?
LeetCode 2091. Removing Minimum and Maximum From Array is tagged Greedy and Array on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview