Longest suffix such that occurrence of each character is less than N after deleting atmost K characters

Given a string S and two integer N and K, the task is to find the maximum length suffix such that occurrence of each character in the suffix string is less than N and atmost K elements can be deleted from the input string to get maximum length suffix.

Examples:

Input: S = “iahagafedcba”, N = 1, K = 0
Output: fedcba
Explanation:
Maximum length suffix in the given string
Such that occurence of each character is 1 is “fedcba”,
Because if we take the string “afedcba”,
then the occurence of character “a” will be 2.

Input: S = “iahagafedcba”, N = 1, K = 2
Output: hgfedcba
Explanation:
Maximum length suffix in the given string
Such that occurrence of each character is 1 is “hgfedcba”,
After deleting character “a” two times.

Approach: The idea is to use hash-map to store the frequency of the characters of the string.



  • Intialize an empty string to store the longest suffix of the string.
  • Iterate the string from last using a loop –
    • Increment the occurrence of the character by 1 in the hash-map
    • If the occurrence of current character is less than N, then add the character into the suffix string
    • Otherwise, decrement the value of K by 1 if the value of K is greater than 0
  • Print the suffix string.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation to find
// longest suffix of the string
// such that occurrence of each 
// character is less than K
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the maximum
// length suffix in the string
void maximumSuffix(string s, 
               int n, int k){
      
    // Length of the string
    int i = s.length() - 1;
  
    // Map to store the number
    // of occurrence of character
    int arr[26] = { 0 };
    string suffix = "";
  
    // Loop to iterate string 
    // from the last character
    while (i > -1) {
  
        int index = s[i] - 'a';
          
        // Condition to check if the 
        // occurrence of each character
        // is less than given number
        if (arr[index] < n) {
            arr[index]++;
            suffix += s[i];
            i--;
            continue;
        }
          
        // Condition when character
        // cannot be deleted
        if (k == 0)
            break;
        k--;
        i--;
    }
    reverse(suffix.begin(), suffix.end());
  
    // Longest suffix
    cout << suffix;
}
  
// Driver Code
int main()
{
    string str = "iahagafedcba";
  
    int n = 1, k = 2;
      
    // Function call
    maximumSuffix(str, n, k);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation to find
// longest suffix of the String
// such that occurrence of each 
// character is less than K
class GFG{
  
// Function to find the maximum
// length suffix in the String
static void maximumSuffix(String s, 
            int n, int k){
      
    // Length of the String
    int i = s.length() - 1;
  
    // Map to store the number
    // of occurrence of character
    int arr[] = new int[26];
    String suffix = "";
      
    // Loop to iterate String 
    // from the last character
    while (i > -1) {
  
        int index = s.charAt(i) - 'a';
          
        // Condition to check if the 
        // occurrence of each character
        // is less than given number
        if (arr[index] < n) {
            arr[index]++;
            suffix += s.charAt(i);
            i--;
            continue;
        }
          
        // Condition when character
        // cannot be deleted
        if (k == 0)
            break;
        k--;
        i--;
    }
    suffix = reverse(suffix);
      
    // Longest suffix
    System.out.print(suffix);
}
static String reverse(String input) {
    char[] a = input.toCharArray();
    int l, r = a.length - 1;
    for (l = 0; l < r; l++, r--) {
        char temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
    return String.valueOf(a);
}
  
// Driver Code
public static void main(String[] args)
{
    String str = "iahagafedcba";
  
    int n = 1, k = 2;
      
    // Function call
    maximumSuffix(str, n, k);
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Python 3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 implementation to find
# longest suffix of the string
# such that occurrence of each 
# character is less than K
  
# Function to find the maximum
# length suffix in the string
def maximumSuffix(s, n, k):
      
    # Length of the string
    i = len(s)- 1
  
    # Map to store the number
    # of occurrence of character
    arr = [0 for i in range(26)]
    suffix = ""
      
    # Loop to iterate string 
    # from the last character
    while (i > -1):
        index = ord(s[i]) - ord('a');
          
        # Condition to check if the 
        # occurrence of each character
        # is less than given number
        if (arr[index] < n):
            arr[index] += 1
            suffix += s[i]
            i -= 1
            continue
          
        # Condition when character
        # cannot be deleted
        if (k == 0):
            break
        k -= 1
        i -= 1
      
    suffix = suffix[::-1]
      
    # Longest suffix
    print(suffix)
  
# Driver Code
if __name__ == '__main__':
    str = "iahagafedcba"
  
    n = 1
    k = 2
      
    # Function call
    maximumSuffix(str, n, k)
  
# This code is contributed by Surendra_Gangwar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation to find
// longest suffix of the String
// such that occurrence of each 
// character is less than K
using System;
  
class GFG{
   
// Function to find the maximum
// length suffix in the String
static void maximumSuffix(String s, 
            int n, int k){
       
    // Length of the String
    int i = s.Length - 1;
   
    // Map to store the number
    // of occurrence of character
    int []arr = new int[26];
    String suffix = "";
       
    // Loop to iterate String 
    // from the last character
    while (i > -1) {
   
        int index = s[i] - 'a';
           
        // Condition to check if the 
        // occurrence of each character
        // is less than given number
        if (arr[index] < n) {
            arr[index]++;
            suffix += s[i];
            i--;
            continue;
        }
           
        // Condition when character
        // cannot be deleted
        if (k == 0)
            break;
        k--;
        i--;
    }
    suffix = reverse(suffix);
       
    // longest suffix
    Console.Write(suffix);
}
static String reverse(String input) {
    char[] a = input.ToCharArray();
    int l, r = a.Length - 1;
    for (l = 0; l < r; l++, r--) {
        char temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
    return String.Join("",a);
}
   
// Driver Code
public static void Main(String[] args)
{
    String str = "iahagafedcba";
   
    int n = 1, k = 2;
       
    // Function call
    maximumSuffix(str, n, k);
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

hgfedcba

Performance Analysis:

  • Time Complexity: In the above-given approach, there is one loop for iterating over string which takes O(L) time in worst case. Therefore, the time complexity for this approach will be O(L).
  • Auxiliary Space Complexity: In the above-given approach, there is extra space used to store the frequency of the character. Therefore, the auxiliary space complexity for the above approach will be O(L)

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 Posts:


Interns at Geeksforgeeks

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.