Related Articles

Related Articles

Lexicographically largest string possible consisting of at most K consecutive similar characters
  • Difficulty Level : Medium
  • Last Updated : 20 Nov, 2020

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 = 2
Output: ccbca

Input: S = “ccbbb”, K = 2
Output: ccbb

Approach: Follow the steps below to solve the problem:



  1. Initialize an array charset[] to store the frequency of each character in the string.
  2. Traverse the string and store the frequency of each character in the array.
  3. Initialize a variable count to store the count of similar consecutive characters
  4. Initialize a string newString to store the resultant string.
  5. Traverse the array charset[] and append (i +’a’) to newString.
  6. Decrease charset[i] and increase count.
  7. 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
  8. Otherwise, reset count to 0.
  9. Repeat steps from 2 to 5 until charset[i] > 0
  10. Finally, return newString.

Below is the implementation of above approach:

C++14

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the
// above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to return nearest
// lower character
char 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 string
string 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 code
int main()
{
  //Given string s
  string S = "ccbbb";
   
  int K = 2;
  cout << (newString(S, K));
}
 
// This code is contributed by Mohit Kumar 29

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java solution for above approach
import 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));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program for the
# above approach
 
# Function to return nearest
# lower character
def 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
# string
def 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 code
if __name__ == "__main__":
 
    # Given string s
    S = "ccbbb"
 
    K = 2
    print(newString(S, K))
 
# This code is contributed by Chitranayal

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# solution for above
// approach
using System;
using System.Text;
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[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 character
static 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 Code
public static void Main(String[] args)
{
  String S = "ccbbb";
  int K = 2;
  Console.WriteLine(
          newString(S, K));
}
}
 
// This code is contributed by Rajput-Ji

chevron_right


Output: 

ccbb









 

Time Complexity: O(N), where N is the length of the given string
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :