#2870

Minimum Number of Operations to Make Array Empty

Medium
ArrayHash TableGreedyCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal approach counts the frequency of each element, then calculates how many operations are needed based on pairs and triplets. This method is efficient because it processes each element only once.

⚙️

Algorithm

3 steps
  1. 1Step 1: Count the frequency of each element in the array using a hashmap.
  2. 2Step 2: For each unique element, determine how many pairs and triplets can be formed.
  3. 3Step 3: Calculate the total number of operations needed to remove all elements.
solution.py13 lines
1from collections import Counter
2
3def min_operations(nums):
4    freq = Counter(nums)
5    operations = 0
6    for count in freq.values():
7        if count % 2 == 1:
8            if count < 3:
9                return -1
10            operations += count // 3 + (count % 3) // 2
11        else:
12            operations += count // 2
13    return operations

Complexity note: The time complexity is O(n) because we only traverse the array once to count frequencies and once more to calculate operations, making it linear in relation to the input size.

  • 1Elements that appear an odd number of times must be handled carefully, as they can't be removed in pairs.
  • 2If an element appears less than 2 times and is odd, it's impossible to remove it.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.