Skip to main content
Back to problems
Leetcode
Medium
Strings
Hash Maps
Arrays
Maximum Difference Between Even And Odd Frequency I

Find the maximum difference between the frequencies of two characters whose counts have opposite parity.

Acceptance 100%
Problem Statement

Maximum Difference Between Even and Odd Frequency I

Given a string s, count how many times each character appears.

Your task is to find the largest possible value of:

frequency of one characterfrequency of another character\text{frequency of one character} - \text{frequency of another character}

subject to the following condition:

  • the first character must have an even frequency,
  • the second character must have an odd frequency,
  • the two characters may be different.

If no valid pair of characters exists, return the closest safe answer for the problem variant, which is typically 0.

This is a frequency-analysis problem where you compare character counts and look for the best even-minus-odd difference.

Input Format

  • A string s consisting of lowercase English letters.
  • You may assume the string is non-empty unless the platform statement says otherwise.

Output Format

  • Return an integer: the maximum value of evenFrequency - oddFrequency over all valid character pairs.
  • If no valid pair exists, return 0.

Constraints

  • 1 <= s.length <= $10^{5}$ is a reasonable interview-style assumption for this variant.
  • Characters are typically lowercase English letters.
  • Time should be linear or near-linear in the length of the string.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.