MediumNo. 2216
Minimum Deletions to Make Array Beautiful — LeetCode 2216 Python Solution
- Pattern
- Stack
- Topics
- Stack, Greedy, Array
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums. The array nums is beautiful if: nums.length is even.
Example
- Input
- nums = [1,1,2,3,5]
- Output
- 1
- Explanation
- You can delete either nums[0] or nums[1] to make nums = [1,2,3,5] which is beautiful. It can be proven you need at least 1 deletion to make nums beautiful.
Python solution
class Solution:
def minDeletion(self, nums: List[int]) -> int:
n = len(nums)
i = ans = 0
while i < n - 1:
if nums[i] == nums[i + 1]:
ans += 1
i += 1
else:
i += 2
ans += (n - ans) % 2
return ansComplexity
- Time
- O(n)where n is the length of the array
- Space · auxiliary
- O(1)
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2216. Minimum Deletions to Make Array Beautiful is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0768 | Max Chunks To Make Sorted II | Hard |
| 0769 | Max Chunks To Make Sorted | Medium |
| 1673 | Find the Most Competitive Subsequence | Medium |
| 1996 | The Number of Weak Characters in the Game | Medium |
| 2818 | Apply Operations to Maximize Score | Hard |
| 2208 | Minimum Operations to Halve Array Sum | Medium |
Frequently asked questions
- How hard is LeetCode 2216. Minimum Deletions to Make Array Beautiful?
LeetCode 2216. Minimum Deletions to Make Array Beautiful is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2216. Minimum Deletions to Make Array Beautiful?
The Python solution on this page runs in O(n), where n is the length of the array.
- What is the space complexity of LeetCode 2216. Minimum Deletions to Make Array Beautiful?
The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2216. Minimum Deletions to Make Array Beautiful cover?
LeetCode 2216. Minimum Deletions to Make Array Beautiful is tagged Stack, Greedy and Array on LeetCode.