Minimum Number of Operations to Make Elements in Array Distinct - Problem
You are given an integer array nums that may contain duplicate elements. Your goal is to make all elements in the array distinct by performing a special removal operation.
In each operation, you can:
- Remove exactly 3 elements from the beginning of the array
- If the array has fewer than 3 elements remaining, remove all remaining elements
Note: An empty array is considered to have distinct elements.
Return the minimum number of operations needed to make all elements in the array distinct.
Example: If nums = [1, 2, 3, 1, 2], we have duplicates (1 and 2 appear twice). We need to remove elements from the front until no duplicates remain.
Input & Output
example_1.py โ Basic Case
$
Input:
[1, 2, 3, 1, 2]
โบ
Output:
2
๐ก Note:
We have duplicates: 1 appears at positions 0 and 3, 2 appears at positions 1 and 4. After 1 operation (removing first 3 elements), we have [1, 2] which still has the duplicates from the original array. After 2 operations (removing all elements), we have an empty array which is considered distinct.
example_2.py โ Already Distinct
$
Input:
[1, 2, 3, 4]
โบ
Output:
0
๐ก Note:
All elements are already distinct, so no operations are needed.
example_3.py โ Single Element
$
Input:
[5]
โบ
Output:
0
๐ก Note:
A single element array is always distinct, so 0 operations are needed.
Constraints
-
0 โค
nums.lengthโค 105 -
1 โค
nums[i]โค 105 - You can only remove elements from the beginning of the array
- Each operation removes exactly 3 elements (or all remaining if < 3)
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Goal
We need all remaining books to be unique (no duplicate titles)
2
Work Backwards
Instead of simulating removals, find the rightmost position where all books to the right are unique
3
Calculate Operations
Once we know how many books to remove from the left, divide by 3 (rounding up) to get operations needed
Key Takeaway
๐ฏ Key Insight: Work backwards to find the rightmost position where the suffix contains only distinct elements, then calculate the minimum operations needed to remove everything to the left of that position.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code