[LeetCode] Minimum Number of Operations to Make Elements in Array Distinct

3396. Minimum Number of Operations to Make Elements in Array Distinct

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 that an empty array is considered to have distinct elements. Return the minimum number of operations needed to make the elements in the array distinct.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int minimumOperations(vector<int>& nums) {
int n = nums.size();
bitset<101> freq;
for(int i = n - 1; i >= 0; i--) {
freq[nums[i]].flip();
if(!freq[nums[i]]) return i/3 + 1;
}
return 0;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/12/22/PS/LeetCode/minimum-number-of-operations-to-make-elements-in-array-distinct/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.