Replace minimal number of characters to make all characters pair wise distinct

Given a string consisting of only lowercase English alphabets. The task is to find and replace the minimal number of characters by any lower case character in the given string such that all pair of characters formed from the string are distinct. If it is impossible to do so print “IMPOSSIBLE”.

Note: If there are more than one answers possible, print the string which is lexicographically smallest.

Examples:



Input : str = “xxxxyyyy”
Output : abcxdefy
In the above example, there are 4 occurence of x and 4 occurence of y so we can change 3 occurence of x to a, b and c and other 3 occurence of y to d, e, f so that all of the characters are pairwise distinct.

Input : str = “theanswerforthistestisimpossible”
Output : IMPOSSIBLE
It is impossible to change characters to make all the characters pairwise distinct.

Approach: The problem is based on the frequency of each character present in the string. If the length of the string is greater than 26 then it is always impossible to make the characters pairwise distinct as there are only 26 lowercase characters in English alphabets.

If the length of the string is less than or equals to 26,

  1. Make a hash array to store the frequency of all characters in the string.
  2. Start traversing the string.
  3. Check if the frequency of the current character in the string is greater than 1.
  4. If Yes, then traverse the hash and find the first character starting from ‘a’ which have not been appeared in the string yet.
  5. Reduce the frequency of the current character in the string and replace the current character in the string by the current character in the hash.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to replace minimal number of
// characters to make all characters
// pair wise distinct
  
#include <iostream>
#include <string>
  
using namespace std;
  
// Function to replace minimal number of
// characters to make all characters
// pair wise distinct
void minReplacement(string str)
{
    // If length of string is greater than 26,
    // it is impossible to make characters
    // pair wise distinct
    if (str.length() > 26)
        cout << "IMPOSSIBLE";
    else {
        // Array to store frequency of each
        // character
        int hash[26] = { 0 };
  
        // Store frequency of each character
        for (int i = 0; i < str.length(); i++)
            hash[str[i] - 'a']++;
  
        int count = 0;
  
        // Start traversing the string
        for (int i = 0; i < str.length(); i++) {
  
            // Check if frequency of current character
            // is greater than 1
            if (hash[str[i] - 'a'] > 1) {
  
                // Traverse the hash
                for (int j = 0; j < 26; j++) {
  
                    // Find the first character starting from 'a'
                    // which have not appeared in the string yet
                    if (hash[j] == 0) {
  
                        // Reduce the frequency of current
                        // character in the string
                        hash[str[i] - 'a']--;
  
                        // Replace the current character in string
                        // by current character in hash
                        str[i] = (char)(j + 'a');
  
                        // Increment the frequency of
                        // this char in hash
                        hash[j]++;
  
                        break;
                    }
                }
            }
        }
  
        // Print the modified string
        cout << str;
    }
}
  
// Driver code
int main()
{
    string str = "xxxxyyyy";
  
    minReplacement(str);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to replace minimal number of 
// characters to make all characters 
// pair wise distinct  
  
class GFG {
  
// Function to replace minimal number of 
// characters to make all characters 
// pair wise distinct 
    static void minReplacement(String str) {
        // If length of String is greater than 26, 
        // it is impossible to make characters 
        // pair wise distinct 
        if (str.length() > 26) {
            System.out.println("IMPOSSIBLE");
        } else {
            // Array to store frequency of each 
            // character 
            int hash[] = new int[26];
  
            // Store frequency of each character 
            for (int i = 0; i < str.length(); i++) {
                hash[str.charAt(i) - 'a']++;
            }
  
            int count = 0;
  
            // Start traversing the String 
            for (int i = 0; i < str.length(); i++) {
  
                // Check if frequency of current character 
                // is greater than 1 
                if (hash[str.charAt(i) - 'a'] > 1) {
  
                    // Traverse the hash 
                    for (int j = 0; j < 26; j++) {
  
                        // Find the first character starting from 'a' 
                        // which have not appeared in the String yet 
                        if (hash[j] == 0) {
  
                            // Reduce the frequency of current 
                            // character in the String 
                            hash[str.charAt(i) - 'a']--;
  
                            // Replace the current character in String 
                            // by current character in hash 
                            str = str.substring(0, i) + (char) (j + 'a') + str.substring(i + 1);
                            //str[i] = (char)(j + 'a'); 
  
                            // Increment the frequency of 
                            // this char in hash 
                            hash[j]++;
  
                            break;
                        }
                    }
                }
            }
  
            // Print the modified String 
            System.out.println(str);
        }
    }
// Driver code 
  
    public static void main(String[] args) {
        String str = "xxxxyyyy";
  
        minReplacement(str);
    }
}
  
/* This Java code is contributed by Rajput-Ji*/

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to replace minimal 
# number of characters to make all 
# characters pair wise distinct 
  
# Function to replace minimal 
# number of characters to make all 
# characters pair wise distinct 
def minReplacement(string): 
  
    # If length of string is greater 
    # than 26, it is impossible to make 
    # characters pair wise distinct 
    if len(string) > 26
        print("IMPOSSIBLE"
    else:
          
        # Array to store frequency of each 
        # character 
        Hash = [0] * 26
  
        # Store frequency of each character 
        for i in range(0, len(string)): 
            Hash[ord(string[i]) - ord('a')] += 1
  
        count = 0
  
        # Start traversing the string 
        for i in range(0, len(string)): 
  
            # Check if frequency of current 
            # character is greater than 1 
            if Hash[ord(string[i]) - ord('a')] > 1
  
                # Traverse the hash 
                for j in range(0, 26): 
  
                    # Find the first character starting from 'a' 
                    # which have not appeared in the string yet 
                    if Hash[j] == 0
  
                        # Reduce the frequency of current 
                        # character in the string 
                        Hash[ord(string[i]) - ord('a')] -= 1
  
                        # Replace the current character in 
                        # string by current character in hash 
                        string[i] = chr(j + ord('a')) 
  
                        # Increment the frequency 
                        # of this char in hash 
                        Hash[j] += 1
  
                        break
  
        # Print the modified string 
        print(''.join(string)) 
      
# Driver code 
if __name__ == "__main__"
  
    string = "xxxxyyyy"
  
    minReplacement(list(string))
      
# This code is contributed by Rituraj Jain

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to replace minimal 
// number of characters to make 
// all characters pair wise distinct 
using System;
                      
class GFG
{
  
// Function to replace minimal number  
// of characters to make all characters 
// pair wise distinct 
static void minReplacement(String str)
{
    // If length of String is greater  
    // than 26, it is impossible to 
    // make characters pair wise distinct 
    if (str.Length > 26) 
    {
        Console.WriteLine("IMPOSSIBLE");
    
    else 
    {
        // Array to store frequency 
        // of each character 
        int []hash = new int[26];
  
        // Store frequency of each character 
        for (int i = 0; i < str.Length; i++) 
        {
            hash[str[i] - 'a']++;
        
        // Start traversing the String 
        for (int i = 0; i < str.Length; i++) 
        {
  
            // Check if frequency of current 
            // character is greater than 1 
            if (hash[str[i] - 'a'] > 1) 
            {
  
                // Traverse the hash 
                for (int j = 0; j < 26; j++)
                {
  
                    // Find the first character 
                    // starting from 'a' which 
                    // have not appeared in the 
                    // String yet 
                    if (hash[j] == 0)
                    {
  
                        // Reduce the frequency of current 
                        // character in the String 
                        hash[str[i] - 'a']--;
  
                        // Replace the current character in
                        // String by current character in hash 
                        str = str.Substring(0, i) + 
                                 (char) (j + 'a') + 
                              str.Substring(i + 1);
                        //str[i] = (char)(j + 'a'); 
  
                        // Increment the frequency of 
                        // this char in hash 
                        hash[j]++;
  
                        break;
                    }
                }
            }
        }
  
        // Print the modified String 
        Console.WriteLine(str);
    }
}
  
// Driver code 
public static void Main() 
{
    String str = "xxxxyyyy";
  
    minReplacement(str);
}
}
  
// This code is contributed
// by Rajput-Ji

chevron_right


PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
// PHP program to replace minimal number 
// of characters to make all characters
// pair wise distinct
  
// Function to replace minimal number 
// of characters to make all characters
// pair wise distinct
function minReplacement($str)
{
    // If length of string is greater than 26,
    // it is impossible to make characters
    // pair wise distinct
    if (strlen($str) > 26)
        echo "IMPOSSIBLE";
    else 
    {
        // Array to store frequency of 
        // each character
        $hash = array_fill(0, 26, NULL);
  
        // Store frequency of each character
        for ($i = 0; $i < strlen($str); $i++)
            $hash[ord($str[$i]) - ord('a')]++;
  
        $count = 0;
  
        // Start traversing the string
        for ($i = 0; $i < strlen($str); $i++) 
        {
  
            // Check if frequency of current 
            // character is greater than 1
            if ($hash[ord($str[$i]) - ord('a')] > 1)
            {
  
                // Traverse the hash
                for ($j = 0; $j < 26; $j++) 
                {
  
                    // Find the first character starting from 'a'
                    // which have not appeared in the string yet
                    if ($hash[$j] == 0)
                    {
  
                        // Reduce the frequency of current
                        // character in the string
                        $hash[ord($str[$i]) - ord('a')]--;
  
                        // Replace the current character in 
                        // string by current character in hash
                        $str[$i] = chr($j + ord('a'));
  
                        // Increment the frequency of
                        // this char in hash
                        $hash[$j]++;
  
                        break;
                    }
                }
            }
        }
  
        // Print the modified string
        echo $str;
    }
}
  
// Driver code
$str = "xxxxyyyy";
minReplacement($str);
  
// This code is contributed by ita_c
?>

chevron_right


Output:

abcxdefy


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.