Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.
If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).
Example 1:
Input: nums = [2,2,1,1,5,3,3,5]
Output: 7
Explanation: For the subarray [2,2,1,1,5,3,3] of length 7, if we remove nums[4]=5, we will get [2,2,1,1,3,3], so that each number will appear exactly twice.
Example 2:
Input: nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
Output: 13
Example 3:
Input: nums = [1,1,1,2,2,2]
Output: 5
Example 4:
Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6]
Output: 8
Constraints:
2 <= nums.length <= 10^5
1 <= nums[i] <= 10^5
from collections import Counter, defaultdict

class Solution:
  def maxEqualFreq(self, nums: List[int]) -> int:
    counter = Counter(nums)
    # d: count -> values has such counts
    d = defaultdict(set)
    for x in counter:
      d[counter[x]].add(x)
    # O(n), reverse go through nums updating count of counts
    i = len(nums)
    while d:
      if len(d) == 1:
        k = list(d.keys())[0]
        if k == 1 or len(d[k]) == 1:
          return i
      if len(d) == 2:
        y, z = sorted(d.keys())
        if (y == 1 and len(d[y]) == 1) or (y + 1 == z and len(d[z]) == 1):
          return i
      i -= 1
      # update counter and count of counts
      x = nums[i]
      d[counter[x]].remove(x)
      if not d[counter[x]]:
        d.pop(counter[x])
      counter[x] -= 1
      if counter[x] > 0:
        d[counter[x]].add(x)
    return 0
from collections import Counter, defaultdict

class Solution:
  def maxEqualFreq(self, nums: List[int]) -> int:
    counter = Counter(nums)
    # d: count -> values has such counts
    d = defaultdict(set)
    for x in counter:
      d[counter[x]].add(x)
    # O(n), reverse go through nums updating count of counts
    i = len(nums)
    while d:
      if len(d) == 1:
        k = list(d.keys())[0]
        if k == 1 or len(d[k]) == 1:
          return i
      if len(d) == 2:
        y, z = sorted(d.keys())
        if (y == 1 and len(d[y]) == 1) or (y + 1 == z and len(d[z]) == 1):
          return i
      i -= 1
      # update counter and count of counts
      x = nums[i]
      d[counter[x]].remove(x)
      if not d[counter[x]]:
        d.pop(counter[x])
      counter[x] -= 1
      if counter[x] > 0:
        d[counter[x]].add(x)
    return 0