Minimum Deletions to Make Array Beautiful - Problem

You are given a 0-indexed integer array nums. The array nums is beautiful if:

  • nums.length is even.
  • nums[i] != nums[i + 1] for all i % 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
Beautiful Array Problem: Transform [1,1,2,3,5] → Beautiful11235❌ Not Beautiful: Odd length + duplicate pairApply Greedy Strategy1234✓ Beautiful: Even length + no duplicate pairsMinimum Deletions: 1
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
Asked in
Google 15 Facebook 12 Amazon 8
23.4K Views
Medium Frequency
~15 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen