Skip to content

2856. Minimum Array Length After Pair Removals

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
 public:
  int minLengthAfterRemovals(vector<int>& nums) {
    const int n = nums.size();
    unordered_map<int, int> count;
    int maxFreq = 0;

    for (const int num : nums)
      ++count[num];

    for (const auto& [_, freq] : count)
      maxFreq = max(maxFreq, freq);

    // The number with the maximum frequency cancel all the other numbers.
    if (maxFreq <= n / 2)
      return n % 2;
    // The number with the maximum frequency cancel all the remaining numbers.
    return maxFreq - (n - maxFreq);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
  public int minLengthAfterRemovals(List<Integer> nums) {
    final int n = nums.size();
    Map<Integer, Integer> count = new HashMap<>();
    int maxFreq = 0;

    for (final int num : nums)
      count.merge(num, 1, Integer::sum);

    for (final int freq : count.values())
      maxFreq = Math.max(maxFreq, freq);

    // The number with the maximum frequency cancel all the other numbers.
    if (maxFreq <= n / 2)
      return n % 2;
    // The number with the maximum frequency cancel all the remaining numbers.
    return maxFreq - (n - maxFreq);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minLengthAfterRemovals(self, nums: list[int]) -> int:
    n = len(nums)
    count = collections.Counter(nums)
    maxFreq = max(count.values())

    # The number with the maximum frequency cancel all the other numbers.
    if maxFreq <= n / 2:
      return n % 2
    # The number with the maximum frequency cancel all the remaining numbers.
    return maxFreq - (n - maxFreq)