#2091

Removing Minimum and Maximum From Array

Medium
ArrayGreedyArrayGreedy
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

The optimal solution leverages the fact that we only need to consider the positions of the minimum and maximum elements and calculate the deletions required in a single pass, leading to a more efficient solution.

⚙️

Algorithm

3 steps
  1. 1Step 1: Find the indices of the minimum and maximum elements in the array.
  2. 2Step 2: Calculate the number of deletions required for three scenarios: removing both from the front, both from the back, and one from each end.
  3. 3Step 3: Return the minimum deletions from the calculated scenarios.
solution.py12 lines
1# Full working Python code
2
3def min_deletions(nums):
4    min_index = nums.index(min(nums))
5    max_index = nums.index(max(nums))
6    front_only = max(min_index, max_index) + 1
7    back_only = len(nums) - min(min_index, max_index)
8    both_ends = min_index + 1 + (len(nums) - max_index)
9    return min(front_only, back_only, both_ends)
10
11# Example usage
12print(min_deletions([2, 10, 7, 5, 4, 1, 8, 6]))  # Output: 5

Complexity note: This complexity is linear because we only traverse the array once to find the indices of the minimum and maximum elements.

  • 1Understanding the positions of the minimum and maximum elements is crucial for determining the number of deletions.
  • 2Only three scenarios need to be considered for deletions: from the front, from the back, or a combination of both.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.