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.
Example 1:
Input: nums = [1,2,3,4,2,3,3,5,7]
Output: 2
Explanation:
- In the first operation, the first 3 elements are removed, resulting in the array
[4, 2, 3, 3, 5, 7]
. - In the second operation, the next 3 elements are removed, resulting in the array
[3, 5, 7]
, which has distinct elements.
Therefore, the answer is 2.
Example 2:
Input: nums = [4,5,6,4,4]
Output: 2
Explanation:
- In the first operation, the first 3 elements are removed, resulting in the array
[4, 4]
. - In the second operation, all remaining elements are removed, resulting in an empty array.
Therefore, the answer is 2.
Example 3:
Input: nums = [6,7,8,9]
Output: 0
Explanation:
The array already contains distinct elements. Therefore, the answer is 0.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
Solution:
class Solution {
public int minimumOperations(int[] nums) {
Set<Integer> visited = new HashSet<>();
for (int i = nums.length - 1; i >= 0; i--){
if (visited.contains(nums[i])){
return (i/3 + 1);
}
visited.add(nums[i]);
}
return 0;
}
}
// TC: O(n)
// SC: O(n)
class Solution {
public int minimumOperations(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
Set<Integer> set = new HashSet<>();
int n = nums.length;
for (int i = 0; i < n; i++){
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
set.add(nums[i]);
}
if (set.size() == n){
return 0;
}
if (n <= 3){
return 1;
}
int result = 0;
int index = 2;
// 0 1 2 3 4 5 6 7 8
// [1,2,3,4,2,3,3,5,7]
// i
//
// r
// 0 1 2 3
// [3, 7, 7, 3]
// i
//
while(index < n){
result++;
int one = nums[index]; // 3 // 7
int two = nums[index - 1]; // 2 // 7
int three = nums[index - 2]; // 1 // 3
map.put(one, map.get(one) - 1); // 3, // <7, 1>
map.put(two, map.get(two) - 1); // 2 // <7, 0>
map.put(three, map.get(three) - 1); // 1
if (map.get(one) == 0){
set.remove(one);
map.remove(one);
}
if (map.containsKey(two) && map.get(two) == 0){
set.remove(two);
map.remove(two);
}
if (map.containsKey(three) && map.get(three) == 0){
set.remove(three);
map.remove(three);
}
// 0 1 2 | 3 4 5 | 6 7 8
// [1,2,3,| 4,2,3,| 3,5,7]
// 8 6 //
// set: 2 3 4 5 7
// map: <1, 1> <2,2> <3,3> <4,1> <5,1> < 7,1>
// <2,1> <3,2> <4,1> <5,1> < 7,1>
// 9 -
if (set.size() == n - 1- index && map.size() == n -1 - index){
return result;
}
index = index + 3;
// 0 1 2 3
// 3 7 7 3
// 2 index
}
if (index != n - 1){
result++;
}
return result;
}
}
// TC: O(n)
// SC: O(n)