Maximum Difference Between Even and Odd Frequency I
Easy · Arrays & Hashing · Explanation and code example
Counting (Optimal)
How it works
Instead of checking all pairs, we can observe that to maximize odd - even, we should pick the largest odd frequency and the smallest even frequency. This gives us the optimal answer in a single pass through the frequency counts.
Steps
- Count the frequency of each character in the string.
- Track
oddMaxas the largest frequency that is odd. - Track
evenMinas the smallest frequency that is even (and greater than0). - Return
oddMax - evenMin.
Complexity
- Time complexity:
O(n) - Space complexity:
O(1)since we have at most26different characters.
Things to watch for
Including Zero Frequencies
Characters that do not appear in the string have frequency zero, which is technically even. However, you cannot use a zero-frequency character as the "even frequency" character because it does not exist in the string. Always filter out zero counts when looking for the minimum even frequency.
Swapping Odd and Even in the Difference
The problem asks for (odd frequency) - (even frequency), not the other way around. Maximizing even - odd instead gives the wrong answer. Pay attention to which frequency should be maximized and which should be minimized.
Python code example
from collections import Counter
class Solution:
def maxDifference(self, s: str) -> int:
count = Counter(s)
oddMax, evenMin = 0, len(s)
for cnt in count.values():
if cnt & 1:
oddMax = max(oddMax, cnt)
else:
evenMin = min(evenMin, cnt)
return oddMax - evenMin
C++ code example
class Solution {
public:
int maxDifference(string s) {
vector<int> count(26, 0);
for (char c : s) {
count[c - 'a']++;
}
int oddMax = 0, evenMin = s.length();
for (int c : count) {
if (c & 1) {
oddMax = max(oddMax, c);
} else if (c > 0) {
evenMin = min(evenMin, c);
}
}
return oddMax - evenMin;
}
};
Source and license
Adapted from NeetCode’s source · MIT license. Node types are supplied by LeetCode where needed.