Program to find minimum required chances to form a string with K unique characters in Python

Suppose we have a string s of lowercase alphabet characters, and another number k. We need to find the minimum number of required changes in the string so that the resulting string has at most k distinct characters. A change means modifying a single character to any other character.

So, if the input is like s = "wxxyyzzxx", k = 3, then the output will be 1, as we can change the letter "w" to get 3 distinct characters (x, y, and z).

Approach

To solve this problem, we will follow these steps ?

  • count := a map of each character in s and their frequency

  • sv := sorted list of frequency values

  • ans := 0

  • for i in range 0 to (size of count) - k - 1, do

    • ans := ans + sv[i]

  • return ans

How It Works

The key insight is to remove characters with the smallest frequencies first. By sorting the frequencies in ascending order, we can eliminate the least frequent characters to minimize total changes.

Example

Let us see the following implementation to get better understanding ?

from collections import Counter

class Solution:
    def solve(self, s, k):
        count = Counter(s)
        sv = sorted(count.values())
        ans = 0
        for i in range(len(count) - k):
            ans += sv[i]
        return ans

ob = Solution()
s = "wxxyyzzxx"
k = 3
print(ob.solve(s, k))

The output of the above code is ?

1

Step-by-Step Execution

Let's trace through the example step by step ?

from collections import Counter

s = "wxxyyzzxx"
k = 3

# Count character frequencies
count = Counter(s)
print("Character frequencies:", count)

# Sort frequencies in ascending order
sv = sorted(count.values())
print("Sorted frequencies:", sv)

# Calculate minimum changes needed
distinct_chars = len(count)
chars_to_remove = distinct_chars - k
print(f"Need to remove {chars_to_remove} character types")

# Sum the smallest frequencies
changes = sum(sv[:chars_to_remove])
print(f"Minimum changes required: {changes}")
Character frequencies: Counter({'x': 4, 'z': 2, 'y': 2, 'w': 1})
Sorted frequencies: [1, 2, 2, 4]
Need to remove 1 character types
Minimum changes required: 1

Alternative Implementation

Here's a more concise version using built-in functions ?

from collections import Counter

def min_changes(s, k):
    freq = Counter(s)
    if len(freq) <= k:
        return 0
    
    sorted_freq = sorted(freq.values())
    return sum(sorted_freq[:len(freq) - k])

# Test the function
s = "wxxyyzzxx"
k = 3
result = min_changes(s, k)
print(f"Minimum changes needed: {result}")
Minimum changes needed: 1

Conclusion

The solution works by counting character frequencies and removing characters with the smallest frequencies first. This greedy approach ensures the minimum number of changes to achieve at most k distinct characters.

Updated on: 2026-03-25T11:13:59+05:30

505 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements