⚡Flashcard Drill➔
NeetCode #145LC-2870MediumArrays & Hashing
← Back to All Problems

#145 · #2870 · Minimum Number of Operations to Make Array Empty(使数组为空的最少操作次数)

📌 Problem Statement & Constraints

You are given an array nums of positive integers. In one operation, remove either two equal elements or three equal elements. Return the minimum number of operations to empty the array, or -1 if it is impossible. Constraints: 2 <= nums.length <= 10^5, 1 <= nums[i] <= 10^6.

💡 Core Algorithmic Approaches

  1. The answer is a sum over each distinct value, since operations never mix different values.
  2. For a frequency c, the minimum number of operations is c // 3 plus 1 if c % 3 != 0, i.e. ceil(c / 3) adjusted: use as many triples as possible, then handle the remainder with a pair.
  3. The only impossible case is c == 1, since a single element cannot be removed by either operation.
  4. Verify the formula: c = 2 -> 1, c = 4 -> 2 (2+2), c = 5 -> 2 (3+2), c = 7 -> 3 (3+2+2), c = 8 -> 3 (3+3+2).

💻 Benchmark Python3 Implementation

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        from collections import Counter
        res = 0
        for c in Counter(nums).values():
            if c == 1:                     # impossible
                return -1
            res += c // 3
            if c % 3:
                res += 1                   # handle the remainder with a pair
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass to count and a constant-size scan over the distinct values.
💾 Space Complexity
O(k) for the counter.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the c == 1 check: a single occurrence can never be removed, so the answer is -1.
  • Using ceil(c / 3) alone: for c = 4 this gives 2, which is correct, but for c = 2 it gives 1 -- also correct. The formula c // 3 + (1 if c % 3 else 0) matches ceil(c / 3) for c >= 2 and is the cleanest way to express it.
  • Using c // 2: removing pairs only is not optimal; triples are more efficient.
  • Aggregating over the whole array instead of per distinct value: operations only work within one value, so the counts must be handled separately.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Arrays & Hashing Problems

中文速览与面试要点

使数组为空的最少操作次数

给你一个下标从 0 开始的正整数数组 nums。你可以对数组执行以下操作任意次:选择数组中的两个或三个 相同 的元素,并把它们从数组中删除。请你返回使数组为空所需的最小操作次数。如果无法使数组为空,返回 −1。约束:2 ≤ nums.length ≤ 10^5;1 ≤ nums[i] ≤ 10^6。

核心要点

  • 按值分组(标准解) :同一值的元素只能互相配对删除,因此每个值的频次是独立的子问题。用 Counter 统计频次。
  • 子问题:用 2 和 3 凑出 c :求最少的加数个数。规律是——c = 1 无解;c = 2 用 1 次(2);c = 3 用 1 次(3);c ≥ 4 时用 ceil(c / 3) 次(优先用 3,余数用 2 补齐)。
  • 为什么 c ≥ 4 时 ceil(c/3) 可行 :c mod 3 == 0 时全用 3;c mod 3 == 1 时用 (c−4)/3 个 3 加 2 个 2;c mod 3 == 2 时用 (c−2)/3 个 3 加 1 个 2。
  • 统一公式 : (c + 2) // 3 ,对 c ≥ 2 均成立(c = 2 → 1、c = 3 → 1、c = 4 → 2、c = 5 → 2、c = 6 → 2、c = 7 → 3)。

常见陷阱

  • 忘记 c == 1 时返回 −1 :频次为 1 的值永远无法删除(至少要 2 个相同元素),整个任务失败,必须返回 −1。
  • 只按 3 分组而忽略 2 :c = 4 时若只考虑 3,会算出 2 次(3 + 剩 1 无法处理);正确做法是用 2 + 2。公式 (c+2)//3 已包含这一情况。
  • 把频次求和后再统一计算 :不同值的元素不能互相配对,必须 按值独立 计算后再求和。
  • 误以为 (c+2)//3 对 c = 1 也适用 :c = 1 时公式给出 1,但实际无解。必须先特判。

参考实现

from collections import Counter

class Solution:
    def minOperations(self, nums: list[int]) -> int:
        cnt = Counter(nums)
        ans = 0
        for c in cnt.values():
            if c == 1:                  # 单个元素无法被删除
                return -1
            ans += (c + 2) // 3         # ceil(c / 3)
        return ans