#2216
Minimum Deletions to Make Array Beautiful
MediumArrayStackGreedyGreedyArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution uses a greedy approach to traverse the array and count the necessary deletions in a single pass. This is efficient because it directly checks adjacent elements without generating subsets.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a counter for deletions and a variable to track the last unique element.
- 2Step 2: Traverse the array, checking pairs of elements at even indices.
- 3Step 3: If the current element is equal to the last unique element, increment the deletion counter.
- 4Step 4: If the length of the array is odd after processing, increment the deletion counter to ensure even length.
solution.py9 lines
1def min_deletions_optimal(nums):
2 deletions = 0
3 n = len(nums)
4 for i in range(0, n - 1, 2):
5 if nums[i] == nums[i + 1]:
6 deletions += 1
7 if (n - deletions) % 2 != 0:
8 deletions += 1
9 return deletionsℹ
Complexity note: This complexity is linear because we only traverse the array once, making constant-time checks for adjacent elements.
- 1Adjacent equal elements must be handled to ensure the beautiful condition.
- 2The final length of the array must be even, which may require an additional deletion.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.