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).

&nbsp;
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


&nbsp;
Constraints:


	2 &lt;= nums.length &lt;= 105
	1 &lt;= nums[i] &lt;= 105


class Solution:
    def maxEqualFreq(self, nums: List[int]) -> int:
        ans = 0
        n = len(nums)
        countToFreq = defaultdict(int)
        # key = count value = Freq ex 2 occured 3 times  in nums so 2 : 3
        freqToCount = defaultdict(int)
        # key = freq value = count ex 2 numbers occured 3 times in nums so 2 : 3
        
        for i,val in enumerate(nums):
            
            x = countToFreq[val] + 1
            freqToCount[x - 1] -= 1
            if freqToCount[x - 1] <= 0 : freqToCount.pop(x - 1)
            freqToCount[x] += 1
            countToFreq[val] = x
            
            # if a single item is repeated for i + 1 times like [1,1,1]
            if countToFreq[val] == i + 1 :ans = i + 1
            
            # if all items are having same frequency like [2,2,1,1,3,3]
            elif (i < n-1 and len(freqToCount) == 1) or (len(freqToCount) == 1 and max(freqToCount.keys())==1): ans = i + 1
            
            # if all items have same frequency except one having 1 freq like [2,2,3,3,1]
            elif len(freqToCount) == 2 and 1 in freqToCount and freqToCount[1] == 1:ans = i +1
            
            # if all items have same frequenct except one having freq common + 1 like[1,1,2,2,3,3,3]
            elif len(freqToCount) == 2:
                keys,values = [],[]
                for j in freqToCount:keys.append(j) , values.append(freqToCount[j])
                if (keys[0]==1+keys[1] and values[0]==1) or (keys[1]==1+keys[0] and values[1]==1):ans = i + 1
        return ans
import java.util.TreeMap;
import java.util.NavigableMap;
class Solution {
    public int maxEqualFreq(int[] nums) {
        Map<Integer, Integer> F          = new HashMap<>(); //Frequencies
        NavigableMap<Integer, Integer> V = new TreeMap<>(); //Values for frequencies
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            increaseCount(F, nums[i]);
            int frequency = F.get(nums[i]);
            decreaseCount(V, frequency - 1);
            increaseCount(V, frequency);
            if (isPossibleToRemove(V)) max = i;
        }
        return max + 1;
    }
    
    public boolean isPossibleToRemove(NavigableMap<Integer, Integer> frequenciesMap) {
        if (frequenciesMap.size() > 2) return false; //more than 2 different frequencies
        Map.Entry<Integer, Integer> first = frequenciesMap.firstEntry();
        Map.Entry<Integer, Integer> last  = frequenciesMap.lastEntry();
        if (frequenciesMap.size() == 1) return first.getKey() == 1 || first.getValue() == 1; //should be [a,a,a,a] or [a,b,c,d]
        int firstReduced = removeElement(first);
        int lastReduced  = removeElement(last);
        if (firstReduced > 0 && lastReduced > 0 && first.getKey() != lastReduced) return false;
        return true;
    }
    
    //Try to remove element which contributes to this frequency:
    //if there's only 1 occurence of such frequency, the frequency itself will become smaller by 1
    //if there are more than 1 occurences of such frequency, removing 1 element will not change it
    public int removeElement(Map.Entry<Integer, Integer> frequencyValue) {
        if (frequencyValue.getValue() == 1) return frequencyValue.getKey() - 1;
        return frequencyValue.getKey();
    }
    
    public void decreaseCount(Map<Integer, Integer> map, int element) {
        if (!map.containsKey(element)) return;
        map.put(element, map.get(element) - 1);
        if (map.get(element) == 0) map.remove(element);
    }
    
    public void increaseCount(Map<Integer, Integer> map, int element) {
        if (!map.containsKey(element)) map.put(element, 0);
        map.put(element, map.get(element) + 1);
    }
}
class Solution {
public:
    int maxEqualFreq(vector<int>& nums) {
        int n=nums.size();
        unordered_map<int,int> mp1,mp2; //one to store the frequency of each number , and one which will store the frequency of the frequency
        int ans=0;
        for(int i=0;i<n;i++)
        {
            int c=nums[i];
            mp1[c]++;
            mp2[mp1[c]]++;
            if(i!=n-1 && mp2[mp1[c]]*mp1[c]==i+1)
            //when curernt length is equal to the total same frequency of numbers then we need one more
            //number which may be anything so doesn't matter .
            //so we just traverse till n-2 and that's it.

                ans=i+2;
            if(mp2[mp1[c]]*mp1[c]==i)
            //when current length is equal to the total same frequency of numbers plus one extra no.
            //( so here taken ==i (i+1-1)) which can be 1. same as any number present 2. different number ..
            //but doesn't matter and our condition just satisfies ... so just take the current length .

                ans=i+1;
        }
        return ans;
    }
};
// *NOTE: ternary operator is to handle if key is undefined since javascript doesn't have a default object value

var maxEqualFreq = function(nums) {
  // create cache to count the frequency of each number
  const numCnt = {};
  
  // create cache to count the number of 'number of frequencies'
  // e.g. [1,2,3,2,4,4,3,1,5]
  //        {  1: 1           1 number appeared with a frequency of 1
  //           2: 3   }      3 numbers appeared with a frequency of 2
  const cntFreq = {};
  
  // holds the maximum frequency a number has appeared
  let maxFreq = 0;
  
  // holds solution
  let result = 0;
  
  // iterate through numbers
  for (let i = 0; i < nums.length; i++) {
      // get current number;
      const num = nums[i];
	  
	  // subtract one from the current frequency of the current number
      cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] - 1 : -1;
	  
	  // increase the count of the current number
      numCnt[num] = numCnt[num] ? numCnt[num] + 1 : 1;
	  
	  // add one to the current frequency of the current number
      cntFreq[numCnt[num]] = cntFreq[numCnt[num]] ? cntFreq[numCnt[num]] + 1 : 1;
	  
	  // if the current frequency is more than the max frequency update the max frequency
      if (maxFreq < numCnt[num]) maxFreq = numCnt[num];
	  
	  // if max frequency is 1 or
	  // if the max frequency multiplied by the number of values with that frequency equals the current index or
	  // if the result of the 1 less than the max frequency equals to the current index
	  // update result
      if (maxFreq === 1 || maxFreq * cntFreq[maxFreq] === i || (maxFreq - 1) * (cntFreq[maxFreq - 1] + 1) === i) {
          result = i + 1;
      }
  }
  return result;
};
Maximum Equal Frequency