#3442

Maximum Difference Between Even and Odd Frequency I

Easy
Hash TableStringCountingHash MapArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(n)
💡

Intuition

Time O(n)Space O(n)

The optimal solution leverages a frequency map to efficiently find the maximum odd frequency and minimum even frequency in a single pass. This reduces the time complexity significantly.

⚙️

Algorithm

4 steps
  1. 1Step 1: Create a frequency map to count occurrences of each character.
  2. 2Step 2: Initialize variables for maximum odd frequency and minimum even frequency.
  3. 3Step 3: Iterate through the frequency map to update the maximum odd and minimum even frequencies in one pass.
  4. 4Step 4: Return the difference between the maximum odd frequency and the minimum even frequency.
solution.py15 lines
1# Full working Python code
2from collections import Counter
3
4def max_diff(s):
5    freq = Counter(s)
6    max_odd = float('-inf')
7    min_even = float('inf')
8    
9    for count in freq.values():
10        if count % 2 == 1:
11            max_odd = max(max_odd, count)
12        else:
13            min_even = min(min_even, count)
14    
15    return max_odd - min_even

Complexity note: The time complexity is O(n) because we only iterate through the string once to build the frequency map and then through the frequency map, which is much smaller than the input size. The space complexity is O(n) due to the storage of character frequencies in the map.

  • 1Identifying odd and even frequencies is crucial for solving the problem.
  • 2Using a frequency map allows efficient counting and comparison.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.