Python program to equal character frequencies

Python provides numerous built-in functions for string manipulation and analysis. In this article, we'll explore how to modify an input string to equalize character frequencies, ensuring each character appears the same number of times as the most frequent character.

Understanding the Problem

Our task is to modify a string so that each character has equal frequencies. We find the maximum occurring character and adjust all other characters to match that frequency.

Example Scenario

Consider this input string:

input_str = "thisisateststring"
print("Original string:", input_str)

# Count character frequencies
from collections import Counter
freq = Counter(input_str)
print("Character frequencies:", dict(freq))
Original string: thisisateststring
Character frequencies: {'t': 4, 'h': 1, 'i': 2, 's': 4, 'a': 1, 'e': 2, 'r': 2, 'n': 2, 'g': 1}

Here, the maximum frequency is 4 (characters 't' and 's'). We need to make all characters appear 4 times, resulting in: thisisateststringhhhiiiaaaeeerrrnnnggg

Method 1: Using count() Method

This approach uses the built-in count() method to find character frequencies and determine the maximum count:

def equalize_frequencies_v1(input_str):
    print(f"Original string: {input_str}")
    
    # Find maximum frequency
    max_count = 0
    for char in set(input_str):
        count = input_str.count(char)
        if count > max_count:
            max_count = count
    
    print(f"Maximum frequency: {max_count}")
    
    # Build new string with equal frequencies
    result = input_str
    for char in set(input_str):
        current_count = input_str.count(char)
        if current_count < max_count:
            result += char * (max_count - current_count)
    
    return result

# Test the function
new_string = equalize_frequencies_v1("thisisateststring")
print(f"Equalized string: {new_string}")
Original string: thisisateststring
Maximum frequency: 4
Equalized string: thisisateststringhhhiiiaaaeeerrrnnnggg

Method 2: Using Counter from Collections

This approach uses Counter for more efficient frequency counting and provides cleaner code:

from collections import Counter

def equalize_frequencies_v2(input_str):
    print(f"Original string: {input_str}")
    
    # Count character frequencies
    char_count = Counter(input_str)
    max_count = max(char_count.values())
    
    print(f"Character frequencies: {dict(char_count)}")
    print(f"Maximum frequency: {max_count}")
    
    # Build equalized string
    result = input_str
    for char, count in char_count.items():
        if count < max_count:
            result += char * (max_count - count)
    
    return result

# Test the function
new_string = equalize_frequencies_v2("hello")
print(f"Equalized string: {new_string}")
Original string: hello
Character frequencies: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
Maximum frequency: 2
Equalized string: helloheo

Comparison

Method Time Complexity Space Complexity Best For
count() O(n²) O(1) Simple implementation
Counter() O(n) O(k) where k = unique chars Better performance

Key Points

The algorithm works by:

  • Finding the maximum character frequency in the string
  • Calculating how many additional characters are needed for each unique character
  • Appending the required number of characters to achieve equal frequencies

Conclusion

Both methods successfully equalize character frequencies, with the Counter approach being more efficient for longer strings. The count() method is simpler but has quadratic time complexity due to repeated string traversals.

Updated on: 2026-03-27T07:35:04+05:30

208 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements