#3779
Minimum Number of Operations to Have Distinct Elements
MediumArrayHash TableHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
Use a hash set to track distinct elements and a pointer to simulate the removal of elements. This approach efficiently checks for duplicates and counts operations.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a set to track distinct elements and a pointer to the start of the array.
- 2Step 2: While duplicates exist, move the pointer forward by three and increment the operation counter.
- 3Step 3: Return the operation count when all elements are distinct.
solution.py10 lines
1def min_operations(nums):
2 seen = set()
3 ops = 0
4 i = 0
5 while i < len(nums):
6 seen.update(nums[i:i+3])
7 i += 3
8 ops += 1
9 if len(seen) == len(nums): break
10 return opsℹ
Complexity note: The algorithm processes each element once and uses a set to track distinct values, leading to linear time complexity.
- 1Removing elements in groups can quickly reduce duplicates.
- 2Using a hash set allows for efficient duplicate checking.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.