[LeetCode] Minimum Number of Operations to Have Distinct Elements

3779. Minimum Number of Operations to Have Distinct Elements

You are given an integer array nums.

In one operation, you remove the first three elements of the current array. If there are fewer than three elements remaining, all remaining elements are removed.

Repeat this operation until the array is empty or contains no duplicate values.

Return an integer denoting the number of operations required.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int minOperations(vector<int>& nums) {
int safe = nums.size();
unordered_map<int,int> freq;
for(int i = nums.size() - 1; i >= 0; i--) {
if(++freq[nums[i]] == 2) break;
safe = i;
}
int until = safe - 1;
if(until == -1) return 0;
return until / 3 + 1;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/04/PS/LeetCode/minimum-number-of-operations-to-have-distinct-elements/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.