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
Minimum Deletions to Make Array Beautiful INPUT nums = [1, 1, 2, 3, 5] 0 1 2 3 4 1 1 2 3 5 Red = to delete (duplicate at even index) Beautiful Array Rules: 1. Length must be even 2. nums[i] != nums[i+1] for all even indices i Problem Found: At index 0 (even): nums[0]=1 == nums[1]=1 ALGORITHM STEPS 1 Initialize deletions = 0, pos = 0 2 Check pairs At even pos, check next 3 Delete if equal Skip element, count++ 4 Ensure even length Add 1 if odd result Greedy Process: i=0: nums[0]=1, nums[1]=1 Equal! Delete nums[1] i=2: nums[0]=1, nums[2]=2 Different! Keep pair i=4: nums[3]=3, nums[4]=5 Different! Keep pair FINAL RESULT Beautiful Array After Deletion: 0 1 2 3 1 2 3 5 [1, 2, 3, 5] Output: 1 Verification: Length = 4 (even) ... OK i=0: 1 != 2 ... OK i=2: 3 != 5 ... OK Array is Beautiful! Key Insight: The greedy approach works because we only need to ensure adjacent elements at even indices are different. When we find nums[i] == nums[i+1] at an even index i, deleting either element fixes the problem. We greedily delete the minimum needed and ensure the final length is even. Time: O(n), Space: O(1). TutorialsPoint - Minimum Deletions to Make Array Beautiful | Greedy Approach
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