
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.
1
We first use Counter from collections to get the frequency of each number in the array. Then, for each frequency, we calculate how many pairs or triples can be removed. We need at least pairs to remove numbers, so if a number appears only once in the list, we return -1. Otherwise, we take the integer division by 3 to count the full groups of 3 elements and add one more operation if there's a remainder. This approach results in efficient calculations to find the minimum operations.
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.
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 while (count >= 2) {
10 if (count === 2 || count === 5) {
11 count -= 2;
12 } else {
13 count -= 3;
14 }
15 operations++;
16 }
17 }
18 return operations;
19}Leveraging an object for frequency counting, a while loop in JS ensures greedily removing triplets where possible before falling back to pairs to achieve a minimal operation count, advancing efficiently over the input.