Skip to main content
Back to problems
#1224
Hard Algorithms

Maximum equal frequency

Array Hash Table
37.9% acceptance
Feb 25, 2026
565
68
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).

Solution

Rust
Time O(n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn max_equal_freq(nums: Vec<i32>) -> i32 {
    use std::collections::HashMap;
    let mut cnt: HashMap<i32, i32> = HashMap::new();
    let mut freq: HashMap<i32, i32> = HashMap::new();
    let mut max_freq = 0i32;
    let mut ans = 0i32;

    for (i, &num) in nums.iter().enumerate() {
      let len = (i + 1) as i32;
      let c = cnt.entry(num).or_insert(0);
      if *c > 0 {
        let f = freq.entry(*c).or_insert(0);
        *f -= 1;
        if *f == 0 { freq.remove(c); }
      }
      *c += 1;
      let c = *c;
      *freq.entry(c).or_insert(0) += 1;
      max_freq = max_freq.max(c);

      let distinct = cnt.len() as i32;
      let max_cnt = *freq.get(&max_freq).unwrap_or(&0);
      let freq1 = *freq.get(&1).unwrap_or(&0);
      let freq_prev = *freq.get(&(max_freq - 1)).unwrap_or(&0);

      let valid =
        len == 1 ||
        max_freq == 1 ||
        // All same freq, remove one occurrence (drop by 1)
        (max_cnt == distinct && (max_freq - 1) * distinct == len - 1) ||
        // One element at max_freq, rest at max_freq-1, remove one occurrence of max_freq element
        (max_cnt == 1 && freq_prev == distinct - 1 && max_freq + (max_freq - 1) * (distinct - 1) == len) ||
        // One element appears once, rest all at max_freq, remove the singleton
        (freq1 == 1 && max_cnt == distinct - 1 && max_cnt * max_freq + 1 == len);

      if valid {
        ans = len;
      }
    }
    ans
  }
}