Lexicographically largest string possible consisting of at most K consecutive similar characters

02 Jun, 2021
Given a string S and an integer K, the task is to generate lexicographically the largest string possible from the given string, by removing characters also, that consists of at most K consecutive similar characters.
Examples:
Input: S = “baccc”, K = 2Output: ccbca
Input: S = “ccbbb”, K = 2Output: ccbb
Approach: Follow the steps below to solve the problem:
Initialize an array charset[] to store the frequency of each character in the string.Traverse the string and store the frequency of each character in the array.Initialize a variable count to store the count of similar consecutive charactersInitialize a string newString to store the resultant string.Traverse the array charset[] and append (i +’a’) to newString.Decrease charset[i] and increase count.Check if count = K and charset[i] > 0, then find the nearest smaller character available from charset[] and append to newString. If the nearest smaller character is not available, then print newStringOtherwise, reset count to 0.Repeat steps from 2 to 5 until charset[i] > 0Finally, return newString.
Initialize an array charset[] to store the frequency of each character in the string.
Traverse the string and store the frequency of each character in the array.
Initialize a variable count to store the count of similar consecutive characters
Initialize a string newString to store the resultant string.
Traverse the array charset[] and append (i +’a’) to newString.
Decrease charset[i] and increase count.
Check if count = K and charset[i] > 0, then find the nearest smaller character available from charset[] and append to newString. If the nearest smaller character is not available, then print newString
Otherwise, reset count to 0.
Repeat steps from 2 to 5 until charset[i] > 0
Finally, return newString.
Below is the implementation of above approach:
C++14
Java
Python3
C#
Javascript
// C++ program for the// above approach#include <bits/stdc++.h>using namespace std; // Function to return nearest// lower characterchar nextAvailableChar(vector<int> charset,                       int start){  // Traverse charset from start-1  for (int i = start - 1; i >= 0; i--)  {    if (charset[i] > 0)    {      charset[i]--;      return char(i + 'a');    }  }  // If no character can be  // appended  return '\0';} // Function to find largest stringstring newString(string originalLabel,                 int limit){  int n = originalLabel.length();     // Stores the frequency of  // characters  vector<int> charset(26, 0);   string newStrings = "";   for(char i : originalLabel)    charset[i - 'a']++;   // Traverse the string  for (int i = 25; i >= 0; i--)  {    int count = 0;     // Append larger character    while (charset[i] > 0)    {      newStrings += char(i + 'a');       // Decrease count in charset      charset[i]--;       // Increase count      count++;       // Check if count reached      // to charLimit      if (charset[i] > 0 &&          count == limit)      {        // Find nearest lower char        char next = nextAvailableChar(charset, i);         // If no character can be        // appended        if (next == '\0')          return newStrings;         // Append nearest lower        // character        newStrings += next;         // Reset count for next        // calculation        count = 0;      }    }  }   // Return new largest string  return newStrings;} //Driver codeint main(){  //Given string s  string S = "ccbbb";     int K = 2;  cout << (newString(S, K));} // This code is contributed by Mohit Kumar 29
// Java solution for above approachimport java.util.*; class GFG {     // Function to find largest string    static String newString(String originalLabel,                            int limit)    {        int n = originalLabel.length();        // Stores the frequency of characters        int[] charset = new int[26];         // Traverse the string        for (int i = 0; i < n; i++) {            charset[originalLabel.charAt(i) - 'a']++;        }         // Stores the resultant string        StringBuilder newString            = new StringBuilder(n);         for (int i = 25; i >= 0; i--) {             int count = 0;             // Append larger character            while (charset[i] > 0) {                 newString.append((char)(i + 'a'));                 // Decrease count in charset                charset[i]--;                 // Increase count                count++;                 // Check if count reached to charLimit                if (charset[i] > 0 && count == limit) {                     // Find nearest lower char                    Character next                        = nextAvailableChar(charset, i);                     // If no character can be appended                    if (next == null)                        return newString.toString();                     // Append nearest lower character                    newString.append(next);                     // Reset count for next calculation                    count = 0;                }            }        }         // Return new largest string        return newString.toString();    }     // Function to return nearest lower character    static Character nextAvailableChar(int[] charset,                                       int start)    {        // Traverse charset from start-1        for (int i = start - 1; i >= 0; i--) {             if (charset[i] > 0) {                 charset[i]--;                return (char)(i + 'a');            }        }        // If no character can be appended        return null;    }    // Driver Code    public static void main(String[] args)    {        String S = "ccbbb";        int K = 2;        System.out.println(newString(S, K));    }}
# Python3 program for the# above approach # Function to return nearest# lower characterdef nextAvailableChar(charset,                      start):     # Traverse charset from start-1    for i in range(start - 1,                   -1, -1):        if (charset[i] > 0):            charset[i] -= 1            return chr(i + ord('a'))               # If no character can be    # appended    return '\0' # Function to find largest# stringdef newString(originalLabel,              limit):     n = len(originalLabel)     # Stores the frequency of    # characters    charset = [0] * (26)     newStrings = ""     for i in originalLabel:        charset[ord(i) -                ord('a')] += 1     # Traverse the string    for i in range(25, -1, -1):        count = 0         # Append larger character        while (charset[i] > 0):            newStrings += chr(i + ord('a'))             # Decrease count in            # charset            charset[i] -= 1             # Increase count            count += 1             # Check if count reached            # to charLimit            if (charset[i] > 0 and                count == limit):                 # Find nearest lower char                next = nextAvailableChar(charset, i)                 # If no character can be                # appended                if (next == '\0'):                    return newStrings                 # Append nearest lower                # character                newStrings += next                 # Reset count for next                # calculation                count = 0     # Return new largest string    return newStrings # Driver codeif __name__ == "__main__":     # Given string s    S = "ccbbb"     K = 2    print(newString(S, K)) # This code is contributed by Chitranayal
// C# solution for above// approachusing System;using System.Text;class GFG{ // Function to find largest stringstatic String newString(String originalLabel,                        int limit){  int n = originalLabel.Length;     // Stores the frequency of  // characters  int[] charset = new int[26];   // Traverse the string  for (int i = 0; i < n; i++)  {    charset[originalLabel[i] - 'a']++;  }   // Stores the resultant string  StringBuilder newString =                new StringBuilder(n);   for (int i = 25; i >= 0; i--)  {    int count = 0;     // Append larger character    while (charset[i] > 0)    {      newString.Append((char)(i + 'a'));       // Decrease count in charset      charset[i]--;       // Increase count      count++;       // Check if count reached      // to charLimit      if (charset[i] > 0 &&          count == limit)      {        // Find nearest lower char        char next =             nextAvailableChar(charset, i);         // If no character can be        // appended        if (next == 0)          return newString.ToString();         // Append nearest lower        // character        newString.Append(next);         // Reset count for next        // calculation        count = 0;      }    }  }   // Return new largest string  return newString.ToString();} // Function to return nearest// lower characterstatic char nextAvailableChar(int[] charset,                              int start){  // Traverse charset from start-1  for (int i = start - 1; i >= 0; i--)  {    if (charset[i] > 0)    {      charset[i]--;      return (char)(i + 'a');    }  }     // If no character can  // be appended  return '\0';} // Driver Codepublic static void Main(String[] args){  String S = "ccbbb";  int K = 2;  Console.WriteLine(          newString(S, K));}} // This code is contributed by Rajput-Ji
<script>// Javascript solution for above approach     // Function to find largest string    function newString(originalLabel,limit)    {        let n = originalLabel.length;                 // Stores the frequency of characters        let charset = new Array(26);         for(let i = 0; i < 26; i++)        {            charset[i] = 0;        }                 // Traverse the string        for (let i = 0; i < n; i++) {            charset[originalLabel[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;        }          // Stores the resultant string        let newString = [];          for (let i = 25; i >= 0; i--) {              let count = 0;              // Append larger character            while (charset[i] > 0) {                  newString.push(String.fromCharCode(i + 'a'.charCodeAt(0)));                  // Decrease count in charset                charset[i]--;                  // Increase count                count++;                  // Check if count reached to charLimit                if (charset[i] > 0 && count == limit) {                      // Find nearest lower char                    let next                        = nextAvailableChar(charset, i);                      // If no character can be appended                    if (next == null)                        return newString.join("");                      // Append nearest lower character                    newString.push(next);                      // Reset count for next calculation                    count = 0;                }            }        }          // Return new largest string        return newString.join("");    }         // Function to return nearest lower character    function nextAvailableChar(charset,start)    {        // Traverse charset from start-1        for (let i = start - 1; i >= 0; i--) {              if (charset[i] > 0) {                  charset[i]--;                return String.fromCharCode(i + 'a'.charCodeAt(0));            }        }        // If no character can be appended        return null;    }         // Driver Code    let S = "ccbbb";    let K = 2;    document.write(newString(S, K)); // This code is contributed by avanitrachhadiya2155</script>
ccbb
 
Time Complexity: O(N), where N is the length of the given stringAuxiliary Space: O(1)
mohit kumar 29
ukasp
Rajput-Ji
avanitrachhadiya2155
Amazon
Amazon-Question
frequency-counting
Greedy
Hash
Searching
Strings
Amazon
Searching
Hash
Strings
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum