Maximum Difference Between Even and Odd Frequency I - Problem

You are given a string s consisting of lowercase English letters. Your task is to find the maximum difference diff = freq(a₁) - freq(a₂) between the frequency of characters a₁ and a₂ in the string such that:

  • a₁ has an odd frequency in the string.
  • a₂ has an even frequency in the string.

Return this maximum difference.

Input & Output

Example 1 — Mixed Frequencies
$ Input: s = "aabbbcc"
Output: 1
💡 Note: Frequencies: a=2 (even), b=3 (odd), c=2 (even). Max odd frequency is 3, min even frequency is 2. Difference = 3 - 2 = 1.
Example 2 — All Even Frequencies
$ Input: s = "abab"
Output: 0
💡 Note: Frequencies: a=2 (even), b=2 (even). No odd frequencies exist, so we cannot form the required difference. Return 0.
Example 3 — Single Character
$ Input: s = "a"
Output: 0
💡 Note: Frequency: a=1 (odd). Only odd frequency exists, no even frequencies to subtract from. Return 0.

Constraints

  • 1 ≤ s.length ≤ 1000
  • s consists of lowercase English letters

Visualization

Tap to expand
Maximum Difference Between Even and Odd Frequency INPUT s = "aabbbcc" a a b b b c c Character Frequencies: Char Freq Type a 2 EVEN b 3 ODD c 2 EVEN ALGORITHM STEPS 1 Count Frequencies Iterate string, count each char 2 Classify by Parity Odd freq: b=3, Even: a=2, c=2 3 Find Max Odd Freq maxOdd = freq(b) = 3 4 Find Min Even Freq minEven = min(2,2) = 2 Calculate Difference: diff = maxOdd - minEven diff = 3 - 2 = 1 FINAL RESULT Maximum Difference Found: ODD b: 3 - EVEN a: 2 = OUTPUT 1 Status: OK 3 - 2 = 1 (Maximum) Key Insight: To maximize diff = freq(odd) - freq(even), find the character with maximum odd frequency and subtract the character with minimum even frequency. One pass through frequency counts suffices. TutorialsPoint - Maximum Difference Between Even and Odd Frequency I | One-Pass Optimal Solution
Asked in
Google 15 Amazon 12 Microsoft 8
12.5K Views
Medium Frequency
~15 min Avg. Time
450 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen