Minimum Number of Operations to Have Distinct Elements Problem
Description
LeetCode Problem 3779.
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.
Example 1:
Input: nums = [3,8,3,6,5,8]
Output: 1
Explanation:
In the first operation, we remove the first three elements. The remaining elements [6, 5, 8] are all distinct, so we stop. Only one operation is needed.
Example 2:
Input: nums = [2,2]
Output: 1
Explanation:
After one operation, the array becomes empty, which meets the stopping condition.
Example 3:
Input: nums = [4,3,5,1,2]
Output: 0
Explanation:
All elements in the array are distinct, therefore no operations are needed.
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Hash Set + Reverse Traversal
Each operation removes the first three elements, so what remains is always a suffix. Walk the array from the end and keep the elements seen so far in a set. If nums[i] is already in the set, the suffix starting at i has a duplicate, so we have to remove the prefix nums[0..i], which takes floor(i / 3) + 1 operations. If we reach the start without a duplicate, the array is already distinct and the answer is 0.
Complexity: time O(n), space O(n), where n is the length of nums.
class Solution:
def minOperations(self, nums: List[int]) -> int:
st = set()
for i in range(len(nums) - 1, -1, -1):
if nums[i] in st:
return i // 3 + 1
st.add(nums[i])
return 0