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 FrequencyInput: "aabbbcc"aabbbccCharacter Frequenciesa: 2 (even)b: 3 (odd)c: 2 (even)Find ExtremesMax Odd: 3Min Even: 2Maximum Difference = 3 - 2 = 1Output: 1
Understanding the Visualization
1
Input String
String with repeating characters
2
Count Frequencies
Count each character's frequency and categorize as odd/even
3
Find Maximum Difference
Max odd frequency minus min even frequency
Key Takeaway
🎯 Key Insight: Find the character with maximum odd frequency and subtract the character with minimum even frequency to get the maximum possible difference.
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