Minimum Deletions to Make Array Beautiful - Problem
You are given a 0-indexed integer array nums. The array nums is beautiful if:
nums.lengthis even.nums[i] != nums[i + 1]for alli % 2 == 0.
Note that an empty array is considered beautiful.
You can delete any number of elements from nums. When you delete an element, all the elements to the right of the deleted element will be shifted one unit to the left to fill the gap created and all the elements to the left of the deleted element will remain unchanged.
Return the minimum number of elements to delete from nums to make it beautiful.
Input & Output
Example 1 — Basic Case
$
Input:
nums = [1,1,2,3,5]
›
Output:
1
💡 Note:
Delete one element to get [1,2,3] which is not beautiful (odd length), or [1,2] which is beautiful. Minimum deletions: 1 (delete either the second 1 or the last 5).
Example 2 — All Same Elements
$
Input:
nums = [1,1,1,1]
›
Output:
2
💡 Note:
All pairs would be identical. Delete 2 elements to get [1,1] then delete both to get [] (empty array is beautiful), or keep alternating elements. Minimum: 2 deletions.
Example 3 — Already Beautiful
$
Input:
nums = [1,2,3,4]
›
Output:
0
💡 Note:
Array has even length and nums[0] ≠ nums[1], nums[2] ≠ nums[3]. Already beautiful, no deletions needed.
Constraints
- 0 ≤ nums.length ≤ 105
- 0 ≤ nums[i] ≤ 105
Visualization
Tap to expand
Understanding the Visualization
1
Input Analysis
Array [1,1,2,3,5] - length 5 (odd), has identical consecutive elements
2
Pairing Strategy
Form pairs greedily: (1,2) and (3,?) - need to handle duplicates and odd length
3
Output
Delete minimum elements to achieve beautiful array
Key Takeaway
🎯 Key Insight: Use greedy pairing strategy - process elements left to right, forming pairs when possible and deleting duplicates
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code