#3396
Minimum Number of Operations to Make Elements in Array Distinct
EasyArrayHash 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)
The optimal approach involves using a set to track distinct elements and counting how many duplicates we have. This allows us to calculate the minimum number of operations needed without repeatedly modifying the array.
⚙️
Algorithm
3 steps- 1Step 1: Create a frequency map to count occurrences of each number.
- 2Step 2: Count how many numbers appear more than once.
- 3Step 3: For each duplicate, calculate how many operations are needed to remove them in groups of three.
solution.py8 lines
1def min_operations(nums):
2 from collections import Counter
3 freq = Counter(nums)
4 operations = 0
5 for count in freq.values():
6 if count > 1:
7 operations += (count - 1) // 3 + 1
8 return operationsℹ
Complexity note: The time complexity is O(n) because we traverse the array once to build the frequency map and then iterate through the map, which is efficient given the constraints.
- 1Using a frequency map helps in efficiently counting duplicates.
- 2Understanding how to group duplicates can minimize operations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.