Minimum Deletions to Make Array Beautiful — LeetCode 2216 Python Solution

MediumStackGreedyArray
Problem
#2216
Pattern
Stack
Reading time
2 min

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 ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(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

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.

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