Skip to content

Commit 191b62e

Browse files
committed
@Solution: Minimum Number of Operations to Make Elements in Array Distinct
1 parent 9044ba3 commit 191b62e

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
# Minimum Number of Operations to Make Elements in Array Distinct
2+
3+
You are given an integer array nums. You need to ensure that the elements in the array are distinct. To achieve this,
4+
you can perform the following operation any number of times:
5+
6+
- Remove 3 elements from the beginning of the array. If the array has fewer than 3 elements, remove all remaining
7+
elements.
8+
9+
**Note** that an empty array is considered to have distinct elements. Return the minimum number of operations needed to make
10+
the elements in the array distinct.
11+
12+
Example 1:
13+
14+
```
15+
Input: nums = [1,2,3,4,2,3,3,5,7]
16+
17+
Output: 2
18+
19+
Explanation:
20+
21+
In the first operation, the first 3 elements are removed, resulting in the array [4, 2, 3, 3, 5, 7].
22+
In the second operation, the next 3 elements are removed, resulting in the array [3, 5, 7], which has distinct elements.
23+
Therefore, the answer is 2.
24+
```
25+
26+
Example 2:
27+
28+
```
29+
Input: nums = [4,5,6,4,4]
30+
31+
Output: 2
32+
33+
Explanation:
34+
35+
In the first operation, the first 3 elements are removed, resulting in the array [4, 4].
36+
In the second operation, all remaining elements are removed, resulting in an empty array.
37+
Therefore, the answer is 2.
38+
```
39+
40+
Example 3:
41+
42+
```
43+
Input: nums = [6,7,8,9]
44+
45+
Output: 0
46+
47+
Explanation:
48+
49+
The array already contains distinct elements. Therefore, the answer is 0.
50+
```
51+
52+
**Constraints:**
53+
54+
- 1 <= nums.length <= 100
55+
- 1 <= nums[i] <= 100
56+
57+
[Link](https://leetcode.com/problems/minimum-number-of-operations-to-make-elements-in-array-distinct/description)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
from typing import List
2+
3+
4+
class Solution:
5+
def minimumOperations(self, nums: List[int]) -> int:
6+
mask = 0
7+
n = len(nums)
8+
for i in reversed(range(n)):
9+
mask ^= 1 << nums[i]
10+
if mask & (1 << nums[i]) == 0:
11+
return (i + 3) // 3
12+
return 0
13+
14+
15+
s = Solution()
16+
print(s.minimumOperations([1, 2, 3, 4, 2, 3, 3, 5, 7]))
17+
print(s.minimumOperations([4, 5, 6, 4, 4]))
18+
print(s.minimumOperations([6, 7, 8, 9]))

0 commit comments

Comments
 (0)