Minimum Number of Operations to Make Elements in Array Distinct - Problem
You are given an integer array nums. You need to ensure that the elements in the array are distinct.
To achieve this, you can perform the following operation any number of times:
- Remove 3 elements from the beginning of the array.
- If the array has fewer than 3 elements, remove all remaining elements.
Note: An empty array is considered to have distinct elements.
Return the minimum number of operations needed to make the elements in the array distinct.
Input & Output
Example 1 — Duplicate Elements
$
Input:
nums = [1,2,1,3,4]
›
Output:
1
💡 Note:
Elements 1 appears twice. Remove first 3 elements [1,2,1], leaving [3,4] which are distinct. One operation needed.
Example 2 — Already Distinct
$
Input:
nums = [1,2,3,4]
›
Output:
0
💡 Note:
All elements are already distinct, so no operations needed.
Example 3 — Small Array with Duplicates
$
Input:
nums = [1,1]
›
Output:
1
💡 Note:
Two duplicate 1s. Since array has less than 3 elements, remove all in one operation.
Constraints
- 1 ≤ nums.length ≤ 105
- -106 ≤ nums[i] ≤ 106
Visualization
Tap to expand
Understanding the Visualization
1
Input Array
Array with duplicate elements that need to be eliminated
2
Remove Operations
Remove 3 elements at a time from the beginning until distinct
3
Result
Return minimum operations needed
Key Takeaway
🎯 Key Insight: Work backwards to find the rightmost duplicate, then calculate how many 3-element removals are needed
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code