Minimum Deletions to Make Array Beautiful — LeetCode 2216 Python Solution
MediumStackGreedyArray
- Problem
- #2216
- Pattern
- Stack
- 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
Python
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
| Measure | Complexity |
|---|---|
| Time | O(n), where n is the length of the array |
| Space | O(1) auxiliary |
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
LeetCode 768Max Chunks To Make Sorted IIHardLeetCode 769Max Chunks To Make SortedMediumLeetCode 1673Find the Most Competitive SubsequenceMediumLeetCode 1996The Number of Weak Characters in the GameMediumLeetCode 2818Apply Operations to Maximize ScoreHardLeetCode 2208Minimum Operations to Halve Array SumMedium
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.