Convert given string so that it holds only distinct characters

Given a string str consisting of lowercase English alphabets, the task is to convert the string so that it holds only distinct characters. Any character of the string can be replaced by any other lowercase character (the number of replacements must be minimum). Print the modified string.

Examples:

Input: str = “geeksforgeeks”
Output: abcdhforgieks

Input: str = “bbcaacgkkk”
Output: dbefacghik

Approach: If the length of the string > 26 then it won’t be possible for the string to have all distinct characters.
Else, count the occurrence for each of the character of the string and for the characters that appear more than once, replace them with some character that hasn’t appeared in the string yet. Print the modified string in the end.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include<bits/stdc++.h>
using namespace std;
  
    // Function to return the index of the character
    // that has 0 occurrence starting from index i
    int nextZero(int i, int occurrences[])
    {
        while (i < 26) 
        {
  
            // If current character has 0 occurrence
            if (occurrences[i] == 0)
                return i;
            i++;
        }
  
        // If no character has 0 occurrence
        return -1;
    }
  
    // Function to return the modified string
    // which consists of distinct characters
    string getModifiedString(string str)
    {
  
        int n = str.length();
  
        // String cannot consist of 
        // all distinct characters
        if (n > 26)
            return "-1";
  
        string ch = str;
  
        int i, occurrences[26] = {0};
  
        // Count the occurences for 
        // each of the character
        for (i = 0; i < n; i++)
            occurrences[ch[i] - 'a']++;
  
        // Index for the first character
        // that hasn't appeared in the string
        int index = nextZero(0, occurrences);
        for (i = 0; i < n; i++) 
        {
  
            // If current character appeared more 
            // than once then it has to be replaced 
            // with some character that
            // hasn't occurred yet
            if (occurrences[ch[i] - 'a'] > 1) 
            {
  
                // Decrement current character's occurrence by 1
                occurrences[ch[i] - 'a']--;
  
                // Replace the character
                ch[i] = (char)('a' + index);
  
                // Update the new character's occurrence
                // This step can also be skipped as 
                // we'll never encounter this character 
                // in the string because it has
                //  been added just now
                occurrences[index] = 1;
  
                // Find the next character that hasn't occurred yet
                index = nextZero(index + 1, occurrences);
            }
        }
    cout << ch << endl;
    }
  
    // Driver code
    int main()
    {
        string str = "geeksforgeeks";
        getModifiedString(str);
    }
      
// This code is contributed by Arnab Kundu

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GFG {
  
    // Function to return the index of the character
    // that has 0 occurrence starting from index i
    static int nextZero(int i, int occurrences[])
    {
        while (i < occurrences.length) {
  
            // If current character has 0 occurrence
            if (occurrences[i] == 0)
                return i;
            i++;
        }
  
        // If no character has 0 occurrence
        return -1;
    }
  
    // Function to return the modified string
    // which consists of distinct characters
    static String getModifiedString(String str)
    {
  
        int n = str.length();
  
        // String cannot consist of all distinct characters
        if (n > 26)
            return "-1";
  
        char ch[] = str.toCharArray();
  
        int i, occurrences[] = new int[26];
  
        // Count the occurences for each of the character
        for (i = 0; i < n; i++)
            occurrences[ch[i] - 'a']++;
  
        // Index for the first character
        // that hasn't appeared in the string
        int index = nextZero(0, occurrences);
        for (i = 0; i < n; i++) {
  
            // If current character appeared more than once then
            // it has to be replaced with some character
            // that hasn't occurred yet
            if (occurrences[ch[i] - 'a'] > 1) {
  
                // Decrement current character's occurrence by 1
                occurrences[ch[i] - 'a']--;
  
                // Replace the character
                ch[i] = (char)('a' + index);
  
                // Update the new character's occurrence
                // This step can also be skipped as we'll never encounter
                // this character in the string because
                // it has been added just now
                occurrences[index] = 1;
  
                // Find the next character that hasn't occurred yet
                index = nextZero(index + 1, occurrences);
            }
        }
  
        // Return the modified string
        return String.valueOf(ch);
    }
  
    // Driver code
    public static void main(String arr[])
    {
        String str = "geeksforgeeks";
        System.out.print(getModifiedString(str));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach
  
# Function to return the index of the character
# that has 0 occurrence starting from index i
def nextZero(i, occurences):
    while i < 26:
  
        # If current character has 0 occurrence
        if occurences[i] == 0:
            return i
        i += 1
  
    # If no character has 0 occurrence
    return -1
  
# Function to return the modified string
# which consists of distinct characters
def getModifiedString(str):
    n = len(str)
  
    # String cannot consist of
    # all distinct characters
    if n > 26:
        return "-1"
  
    ch = str
    ch = list(ch)
    occurences = [0] * 26
  
    # Count the occurences for
    # each of the character
    for i in range(n):
        occurences[ord(ch[i]) - ord('a')] += 1
  
    # Index for the first character
    # that hasn't appeared in the string
    index = nextZero(0, occurences)
  
    for i in range(n):
  
        # If current character appeared more
        # than once then it has to be replaced
        # with some character that
        # hasn't occurred yet
        if occurences[ord(ch[i]) - ord('a')] > 1:
  
            # Decrement current character's occurrence by 1
            occurences[ord(ch[i]) - ord('a')] -= 1
  
            # Replace the character
            ch[i] = chr(ord('a') + index)
  
            # Update the new character's occurrence
            # This step can also be skipped as
            # we'll never encounter this character
            # in the string because it has
            # been added just now
            occurences[index] = 1
  
            # Find the next character 
            # that hasn't occurred yet
            index = nextZero(index + 1, occurences)
  
    ch = ''.join(ch)
    print(ch)
  
# Driver code
if __name__ == "__main__":
    str = "geeksforgeeks"
    getModifiedString(str)
  
# This code is contributed by
# sanjeev2552

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach 
using System;
  
class GFG 
  
    // Function to return the index of the character 
    // that has 0 occurrence starting from index i 
    static int nextZero(int i, int []occurrences) 
    
        while (i < occurrences.Length) 
        
  
            // If current character has 0 occurrence 
            if (occurrences[i] == 0) 
                return i; 
            i++; 
        
  
        // If no character has 0 occurrence 
        return -1; 
    
  
    // Function to return the modified string 
    // which consists of distinct characters 
    static string getModifiedString(string str) 
    
  
        int n = str.Length ; 
  
        // String cannot consist of all distinct characters 
        if (n > 26) 
            return "-1"
          
        char []ch = str.ToCharArray(); 
        int []occurrences = new int[26]; 
        int i ;
  
        // Count the occurences for each of the character 
        for (i = 0; i < n; i++) 
            occurrences[ch[i] - 'a']++; 
  
        // Index for the first character 
        // that hasn't appeared in the string 
        int index = nextZero(0, occurrences); 
        for (i = 0; i < n; i++)
        
  
            // If current character appeared more than  
            // once then it has to be replaced with some  
            // character that hasn't occurred yet 
            if (occurrences[ch[i] - 'a'] > 1)
            
  
                // Decrement current character's occurrence by 1 
                occurrences[ch[i] - 'a']--; 
  
                // Replace the character 
                ch[i] = (char)('a' + index); 
  
                // Update the new character's occurrence 
                // This step can also be skipped 
                // as we'll never encounter 
                // this character in the string because 
                // it has been added just now 
                occurrences[index] = 1; 
  
                // Find the next character that hasn't occurred yet 
                index = nextZero(index + 1, occurrences); 
            
        
  
        string s = new string(ch) ;
  
        // Return the modified string 
        return s ;
    
  
    // Driver code 
    public static void Main() 
    
        string str = "geeksforgeeks"
        Console.WriteLine(getModifiedString(str)); 
    
      
// This code is contributed by Ryuga

chevron_right


Output:

abcdhforgieks


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.





Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.