Minimum Deletions to Make Array Beautiful - Problem
Transform an Array into Beautiful Harmony!
You're given a
An array is considered beautiful if:
• It has an even length (including 0)
• For all even indices
In other words, every pair at positions
Key Rules:
• When you delete an element, all elements to the right shift left
• An empty array is considered beautiful
• Return the minimum number of deletions needed
Goal: Find the minimum deletions to create alternating pairs of different values!
You're given a
0-indexed integer array nums, and your mission is to make it beautiful with the minimum number of deletions possible.An array is considered beautiful if:
• It has an even length (including 0)
• For all even indices
i, we have nums[i] ≠ nums[i + 1]In other words, every pair at positions
(0,1), (2,3), (4,5), etc. must contain different values.Key Rules:
• When you delete an element, all elements to the right shift left
• An empty array is considered beautiful
• Return the minimum number of deletions needed
Goal: Find the minimum deletions to create alternating pairs of different values!
Input & Output
example_1.py — Basic Case
$
Input:
[1,1,2,3,5]
›
Output:
1
💡 Note:
We can delete the first 1 to get [1,2,3,5]. This array has even length (4) and forms pairs (1,2) and (3,5) where each pair has different values, making it beautiful.
example_2.py — All Same Elements
$
Input:
[1,1,1,1]
›
Output:
2
💡 Note:
Since all elements are the same, we cannot form any valid pairs. We need to delete at least 2 elements to get an empty array (which is beautiful) or delete 2 elements to get [1,1] then delete both to get empty array.
example_3.py — Already Beautiful
$
Input:
[1,2,3,4]
›
Output:
0
💡 Note:
The array is already beautiful: it has even length (4) and pairs (1,2) and (3,4) both have different values. No deletions needed.
Constraints
- 1 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 105
- Array elements can be any non-negative integers
- Must return minimum number of deletions
Visualization
Tap to expand
Understanding the Visualization
1
Scan Left to Right
Start from the beginning, examining consecutive dancers
2
Different Colors? Pair Them!
When two dancers have different outfit colors, form a valid pair
3
Same Colors? Remove One
When colors match, remove the current dancer to avoid invalid pair
4
Handle Odd Remainder
If one dancer is left unpaired at the end, remove them too
Key Takeaway
🎯 Key Insight: Greedy pairing works optimally because removing a dancer when colors match is always the right choice - there's no benefit to keeping duplicate colors together, and forming valid pairs immediately maximizes our efficiency!
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code