Sponsored
Sponsored
This approach leverages the frequency count of each number to determine the minimum number of operations needed. We will iterate over the frequency list and for each number, calculate the possible number of operations (either removing two or three elements at a time).
Time Complexity: O(n), where n is the length of the array, as we are iterating through the array and frequencies. Space Complexity: O(n) for storing the frequency count.
1function minOperations(nums) {
2 const freq = {};
3 nums.forEach(num => {
4 freq[num] = (freq[num] || 0) + 1;
5 });
6 let operations = 0;
7 for (let count of Object.values(freq)) {
8 if (count === 1) return -1;
9 operations += Math.ceil(count / 3);
10 }
11 return operations;
12}
In JavaScript, we employ an object to calculate frequencies. We check if each number's frequency is one, returning -1 if true. By using Math.ceil(count / 3)
, we determine the ceiling of the division, which helps calculate how many sets of triples can be removed effectively.
This approach targets optimizing operations by prioritizing pair removals wherever possible, then triples. The main idea is to use as many pair removals as possible, and only use triples to fill gaps that pairs cannot cover fully.
Time Complexity: O(n), both for listing and iterating through frequencies. Space Complexity: O(n) for the frequency map.
1from
Using Counter
for frequency counts, we iterate through controlling operations greedily by continuously subtracting 3 (for triples) unless only a single pair remains. This logic ensures minimal operations by prioritizing large removals over small ones unless strictly necessary.