Problem
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.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 100
Solution
Method 1 - Using Hashset🧠
The problem requires ensuring all elements in the array are distinct, with the provided operation of removing up to three elements from the beginning of the array. The goal is to find the minimum number of operations required to make all elements in the array unique.
Intuition 🧠
The goal is to minimise the number of operations by identifying how soon a duplicate occurs when the array is traversed in reverse. On encountering the first duplicate, we calculate the number of operations required to ensure all elements are unique (or address the violation of the given condition).
Approach 🛠️
- Iterate through the array starting from the end towards the beginning.
- Maintain a set to track elements that have already been seen.
- As 🛠️ as a duplicate is found, return
i // 3 + 1
, representing the minimum operations needed. - If no duplicates are found, return
0
.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
as we iterate through each array element once. - 🧺 Space complexity:
O(n)
. In the worst case, we might store all elements in the set if there are no duplicates.