Problem Description
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. Note that if after removing one element there are no remaining elements, it’s still considered valid because every (zero) number has the same frequency.
Key Insights
- Use a hash table (dictionary) to count occurrences of each number.
- Use another hash table to count how many numbers have a specific frequency.
- As you iterate over the prefix, update both hash tables.
- At each step, check a few conditions that would allow the array (after one removal) to have equal frequencies:
- All numbers occur only once.
- All numbers have the same frequency except one number that occurs exactly once.
- All numbers have the same frequency except one number that has one more occurrence than the others.
- Update the maximum valid prefix length when any of these conditions hold.
Space and Time Complexity
Time Complexity: O(n), where n is the number of elements, because we process each element in constant time. Space Complexity: O(n), owing to the storage required for the hash tables.
Solution
We will iterate through the nums array and maintain two hash maps:
- count: maps each number to its frequency.
- freq: maps each frequency to the count of numbers with that frequency.
For each element in the prefix:
- Increase its count.
- Update the freq hash table accordingly.
- Check whether the current state satisfies one of the valid conditions:
- When all numbers are seen once.
- When there is exactly one number with frequency 1 and all other numbers have the same frequency.
- When there is exactly one number with a frequency that is one greater than the frequency of all other numbers. If any condition is satisfied, record the current index as the longest valid prefix.