LeetCode 2870. Minimum Number of Operations to Make Array Empty
Intuition
- Mathematics problem.
- Count the number of occurrences for all numbers in
nums. - Specify the operation based on the number of occurrences.
Approach
The number of operations required to remove a specific number of occurrences can be found as follows:
| Number of Occurrences | Number of Operations to Remove this Number |
|---|---|
| 1 | -1 (no solution) |
| 2 / 3 | 1 |
| 4 / 5 / 6 | 2 |
| 7 / 8 / 9 | 3 |
| 10 / 11 / 12 | 4 |
| … | … |
| n-2 / n-1 / n | $\lceil n/3 \rceil$ |
- Create an empty map
count. - Initialise
ansto 0. - Count the number of occurrences for every number in
nums, and store it incount. - Use the table above to calculate the number of operations needed.
- Return
ans.
Pseudocode of minOperations():
1 | minOperations(): |
Complexity
Time complexity: $O(n)$.
- $n$ iterations to count the number of occurances in the array.
Space complexity: $O(n)$.
countwill take a space of $n$ if all the numbers in the array are unique.
Code
1 | class Solution { |