Facebook Pixel

3442. Maximum Difference Between Even and Odd Frequency I

EasyHash TableStringCounting
Leetcode Link

Problem Description

You are given a string s consisting of lowercase English letters. Your task is to find the maximum difference between the frequency of two characters in the string such that:

  • One of the characters has an even frequency in the string.
  • The other character has an odd frequency in the string.

Return the maximum difference, calculated as the frequency of the character with an odd frequency minus the frequency of the character with an even frequency.

Intuition

The goal is to identify two characters within the string such that the difference between their frequencies maximizes the condition where one has an odd frequency and the other has an even frequency.

To solve this, we can use a frequency counter to tally the occurrences of each character in s. The strategy involves two main steps:

  1. Tracking Frequencies: First, collect the frequencies of each character using a hash table or an array. This helps identify how many times each character appears in the string.

  2. Determine Maximum and Minimum Frequencies: Next, iterate through the frequency values to find:

    • The maximum frequency among characters that appear an odd number of times (a).
    • The minimum frequency among characters that appear an even number of times (b).

Finally, return the result of the subtraction a - b, representing the maximum frequency difference as per the defined criteria.

Solution Approach

To find the maximum difference between the frequencies of two characters in s such that one has an odd frequency and the other has an even frequency, the following approach can be used:

  1. Use a Frequency Counter: Utilize a hash table (specifically, Python's Counter from the collections module) to count the occurrences of each character in the string s. This helps track how many times each character appears.

  2. Initialize Tracking Variables:

    • Let a represent the maximum frequency of characters with odd counts. Start with 0 as the initial value since it needs to be maximized.
    • Let b represent the minimum frequency of characters with even counts. Begin with positive infinity (inf) as the initial value because it needs to be minimized.
  3. Iterate Through Frequencies:

    • For each frequency value v from the frequency counter:
      • If v is odd, update a to be the maximum of its current value and v.
      • If v is even, update b to be the minimum of its current value and v.
  4. Compute the Result: Calculate the difference a - b and return it. This difference represents the maximum difference between character frequencies with the desired properties.

The code implements this approach effectively:

class Solution:
    def maxDifference(self, s: str) -> int:
        cnt = Counter(s)  # Count frequencies of each character
        a, b = 0, inf  # Initialize max odd frequency and min even frequency
        for v in cnt.values():
            if v % 2:
                a = max(a, v)  # Update max odd frequency
            else:
                b = min(b, v)  # Update min even frequency
        return a - b  # Return the calculated difference

This method efficiently uses counting and comparison operations to achieve the desired outcome.

Ready to land your dream job?

Unlock your dream job with a 2-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's take a small example string s = "abacacbba". Our goal is to find the maximum difference between the frequency of two characters such that one has an even frequency and the other has an odd frequency.

  1. Use a Frequency Counter: Count the occurrences of each character.

    • 'a': 4 times
    • 'b': 3 times
    • 'c': 2 times
  2. Initialize Tracking Variables:

    • a = 0: This will track the maximum frequency among characters with odd frequencies.
    • b = inf: This will track the minimum frequency among characters with even frequencies.
  3. Iterate Through Frequencies:

    • For 'a' with a frequency of 4 (even), set b = min(inf, 4), so b = 4.
    • For 'b' with a frequency of 3 (odd), set a = max(0, 3), so a = 3.
    • For 'c' with a frequency of 2 (even), set b = min(4, 2), so b = 2.
  4. Compute the Result: The maximum difference is a - b = 3 - 2 = 1.

Thus, for the string s = "abacacbba", the maximum difference between the frequencies of a character with an odd frequency and a character with an even frequency is 1.

Solution Implementation

1# Required imports
2from collections import Counter
3from math import inf
4
5class Solution:
6    def maxDifference(self, s: str) -> int:
7        # Count the frequency of each character in the string
8        char_count = Counter(s)
9      
10        # Initialize variables to track the maximum odd count and minimum even count
11        max_odd_count = 0
12        min_even_count = inf
13      
14        # Iterate over the frequency values
15        for count in char_count.values():
16            if count % 2:  # If the count is odd
17                max_odd_count = max(max_odd_count, count)
18            else:  # If the count is even
19                min_even_count = min(min_even_count, count)
20      
21        # Return the difference between the maximum odd count and minimum even count
22        return max_odd_count - min_even_count
23
1class Solution {
2    public int maxDifference(String s) {
3        int[] frequency = new int[26];  // Array to hold the frequency of each character (a-z) in the string
4
5        // Populate the frequency array with the count of each character in the string
6        for (char c : s.toCharArray()) {
7            frequency[c - 'a']++;
8        }
9
10        int maxOddFrequency = 0;  // Variable to track the maximum frequency of characters appearing an odd number of times
11        int minEvenFrequency = Integer.MAX_VALUE;  // Variable to track the minimum frequency of characters appearing an even number of times
12
13        // Iterate through the frequency array
14        for (int count : frequency) {
15            if (count % 2 == 1) {  // Check if the frequency is odd
16                maxOddFrequency = Math.max(maxOddFrequency, count);  // Update maxOddFrequency if a larger odd frequency is found
17            } else if (count > 0) {  // Check if the frequency is even and greater than zero
18                minEvenFrequency = Math.min(minEvenFrequency, count);  // Update minEvenFrequency if a smaller even frequency is found
19            }
20        }
21
22        // Return the difference between max odd frequency and min even frequency
23        return maxOddFrequency - minEvenFrequency;
24    }
25}
26
1class Solution {
2public:
3    int maxDifference(string s) {
4        int counts[26] = {};  // Array to store count of each lowercase letter
5      
6        // Count occurrences of each character in the string
7        for (char c : s) {
8            ++counts[c - 'a'];
9        }
10      
11        int maxOddCount = 0;              // Maximum count of characters with odd occurrence
12        int minEvenCount = 1 << 30;       // Minimum count of characters with even occurrence
13
14        // Iterate through the counts array
15        for (int count : counts) {
16            // If the count is odd and greater than current maxOddCount, update maxOddCount
17            if (count % 2 == 1) {
18                maxOddCount = max(maxOddCount, count);
19            }
20            // If the count is even and greater than zero, update minEvenCount with the smaller value
21            else if (count > 0) {
22                minEvenCount = min(minEvenCount, count);
23            }
24        }
25      
26        // Return the difference between maximum odd count and minimum even count
27        return maxOddCount - minEvenCount;
28    }
29};
30
1function maxDifference(s: String): number {
2    const characterCount: Record<string, number> = {};
3  
4    // Count the occurrences of each character in the string
5    for (const char of s) {
6        characterCount[char] = (characterCount[char] || 0) + 1;
7    }
8
9    // Initialize values for max odd occurrence and min even occurrence
10    let maxOddOccurrence = 0;
11    let minEvenOccurrence = Infinity;
12
13    // Iterate over the counted occurrences
14    for (const [, count] of Object.entries(characterCount)) {
15        if (count % 2 === 1) {
16            // Update maxOddOccurrence for characters with odd counts
17            maxOddOccurrence = Math.max(maxOddOccurrence, count);
18        } else {
19            // Update minEvenOccurrence for characters with even counts
20            minEvenOccurrence = Math.min(minEvenOccurrence, count);
21        }
22    }
23
24    // Calculate the difference between max odd and min even occurrences
25    return maxOddOccurrence - minEvenOccurrence;
26}
27

Time and Space Complexity

The time complexity of the code is O(n), where n is the length of the string s. This is because the code involves iterating over the string once to count the occurrences of each character, and then iterating over the counted values.

The space complexity is O(|Σ|), where |Σ| is the size of the character set, which is 26 for lowercase English letters. The space is used to store the count of each character.

Learn more about how to find time and space complexity quickly.


Discover Your Strengths and Weaknesses: Take Our 2-Minute Quiz to Tailor Your Study Plan:
Question 1 out of 10

What are the most two important steps in writing a depth first search function? (Select 2)


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!


Load More