Given a string consisting of only lowercase English alphabets. The task is to find and replace the minimal number of characters with any lower case character in the given string such that all pairs of characters formed from the string are distinct. If it is impossible to do so, print “IMPOSSIBLE”.
Note: If there is more than one answer possible, print the string which is lexicographically smallest.
Examples:
Input : str = “xxxxyyyy”
Output : abcxdefy
In the above example, there are 4 occurrences of x and 4 occurrences of y, so we can change 3 occurrences of x to a, b and c and another 3 occurrences 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 the English alphabet.
If the length of the string is less than or equals 26,
- Make a hash array to store the frequency of all characters in the string.
- Start traversing the string.
- Check if the frequency of the current character in the string is greater than 1.
- If Yes, then traverse the hash and find the first character starting from ‘a’ which has not appeared in the string yet.
- Reduce the frequency of the current character in the string and replace the current character in the string with the current character in the hash.
Below is the implementation of the above approach:
// 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;
} |
// 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*/ |
# 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 |
// 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 |
<?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 ?> |
<script> // Javascript 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 (str.length > 26) {
document.write( "IMPOSSIBLE<br>" );
}
else {
// Array to store frequency of each
// character
let hash = new Array(26);
for (let i=0;i<26;i++)
{
hash[i]=0;
}
// Store frequency of each character
for (let i = 0; i < str.length; i++) {
hash[str[i].charCodeAt(0) - 'a' .charCodeAt(0)]++;
}
let count = 0;
// Start traversing the String
for (let i = 0; i < str.length; i++) {
// Check if frequency of current character
// is greater than 1
if (hash[str[i].charCodeAt(0) - 'a' .charCodeAt(0)] > 1) {
// Traverse the hash
for (let 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].charCodeAt(0) - 'a' .charCodeAt(0)]--;
// Replace the current character in String
// by current character in hash
str = str.substring(0, i) +
String.fromCharCode(j + 'a' .charCodeAt(0)) +
str.substring(i + 1);
//str[i] = (char)(j + 'a');
// Increment the frequency of
// this char in hash
hash[j]++;
break ;
}
}
}
}
// Print the modified String
document.write(str);
}
}
// Driver code
let str = "xxxxyyyy" ;
minReplacement(str);
// This code is contributed by rag2127 </script> |
abcxdefy
Complexity Analysis:
- Time Complexity: O(N), where N is the length of the string
- Auxiliary Space: O(1)