Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Minimum operations required to convert all characters of a String to a given Character
Next article icon

Minimum length of Run Length Encoding possible by removing at most K characters from a given string

Last Updated : 29 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S of length N, consisting of lowercase English alphabets only, the task is to find the minimum possible length of run-length-encoding that can be generated by removing at most K characters from the string S.

Examples:

Input: S = “abbbcdcdd”, N = 9, K = 2 
Output: 5 
Explanation: One possible way is to delete both occurrences of ‘c’ from S.
The new string generated is “abbbddd” whose run-length-encoding is “ab3d3”. 
Therefore, the length of the encoded string is 5.

Input: S = “aabbca”, N = 6, K = 3 
Output: 2 
Explanation: One possible way is to delete both the occurrences of ‘b’ and one occurrence of ‘c’. 
The new string generated is “aaa” whose run-length-encoding is “a3”. 
Therefore, the length of the encoded string is 2

Naive Approach: The simplest approach to solve the problem is to remove every combination of K characters from the string and calculate their respective run-length-encoding. Finally, print the length of the smallest run-length-encoding obtained. 

Time Complexity: O(K * N!(N – K)! * K!) 
Auxiliary Space: O(K)

Efficient Approach: To optimize the above approach, follow the steps below to solve the problem:

  • Maintain an auxiliary array dp[n][k][26][n], where dp[idx][K][last][count] denotes the minimum run-length-encoding obtained starting from index idx where, K denotes the number of deletions remaining, last denotes the last character with frequency count so far.
  • For every character, two possibilities exists, either to delete the character or to retain it.
  • Consider that the current character at index idx is deleted and calculate recursively the minimum run-length encoding obtained by passing the parameters (idx + 1, K – 1, last, count)
  • Now, consider that the current character at index idx is retained and calculate recursively the minimum run-length encoding for the following two cases:
  • If S[idx] = last: Calculate minimum run-length encoding by passing the parameters (idx + 1, K, S[idx], count + 1).
  • Otherwise, calculate minimum run-length encoding by passing the parameters (idx + 1, K, S[idx], 1).
  • Return the minimum of the above-computed values and repeat the above steps for all indices of the string.

Below is the implementation of the above approach:

C++




// C++ Program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
#define maxN 20
 
int dp[maxN][maxN][27][maxN];
 
// Function which solves the desired problem
int solve(string& s, int n, int idx,
          int k, char last = 123,
          int count = 0)
{
    // idx: current index in s
    // k: Remaining number of deletions
    // last: Previous character
    // count: Number of occurrences
    // of the previous character
 
    // Base Case
    if (k < 0)
        return n + 1;
 
    // If the entire string has
    // been traversed
    if (idx == n)
        return 0;
 
    int& ans = dp[idx][k][last - 'a'][count];
 
    // If precomputed subproblem
    // occurred
    if (ans != -1)
        return ans;
 
    ans = n + 1;
 
    // Minimum run length encoding by
    // removing the current character
    ans = min(ans,
              solve(s, n, idx + 1, k - 1, last, count));
 
    // Minimum run length encoding by
    // retaining the current character
    int inc = 0;
 
    if (count == 1 || count == 9
        || count == 99)
        inc = 1;
 
    // If the current and the
    // previous characters match
    if (last == s[idx]) {
 
        ans = min(ans,
                  inc + solve(s, n, idx + 1, k, s[idx],
                              count + 1));
    }
 
    // Otherwise
    else {
 
        ans = min(ans,
                  1 + solve(s, n, idx + 1, k, s[idx], 1));
    }
 
    return ans;
}
 
// Function to return minimum run-length encoding
// for string s by removing atmost k characters
int MinRunLengthEncoding(string& s, int n, int k)
{
    memset(dp, -1, sizeof(dp));
    return solve(s, n, 0, k);
}
 
// Driver Code
int main()
{
    string S = "abbbcdcdd";
    int N = 9, K = 2;
    cout << MinRunLengthEncoding(S, N, K);
 
    return 0;
}
 
 

Java




// Java program to implement
// the above approach
import java.util.*;
 
class GFG{
 
static int maxN = 20;
 
static int dp[][][][] = new int[maxN][maxN][27][maxN];
 
// Function which solves the desired problem
public static int solve(String s, int n,
                         int idx, int k,
                       char last, int count)
{
     
    // idx: current index in s
    // k: Remaining number of deletions
    // last: Previous character
    // count: Number of occurrences
    // of the previous character
 
    // Base Case
    if (k < 0)
        return n + 1;
 
    // If the entire string has
    // been traversed
    if (idx == n)
        return 0;
 
    int ans = dp[idx][k][last - 'a'][count];
 
    // If precomputed subproblem
    // occurred
    if (ans != -1)
        return ans;
 
    ans = n + 1;
 
    // Minimum run length encoding by
    // removing the current character
    ans = Math.min(ans, solve(s, n, idx + 1,
                              k - 1, last,
                              count));
 
    // Minimum run length encoding by
    // retaining the current character
    int inc = 0;
 
    if (count == 1 || count == 9 || count == 99)
        inc = 1;
 
    // If the current and the
    // previous characters match
    if (last == s.charAt(idx))
    {
        ans = Math.min(ans, inc + solve(s, n, idx + 1,
                                        k, s.charAt(idx),
                                        count + 1));
    }
 
    // Otherwise
    else
    {
        ans = Math.min(ans, 1 + solve(s, n, idx + 1, k,
                                      s.charAt(idx), 1));
    }
    return dp[idx][k][last - 'a'][count] = ans;
}
 
// Function to return minimum run-length encoding
// for string s by removing atmost k characters
public static int MinRunLengthEncoding(String s, int n,
                                                 int k)
{
    for(int i[][][] : dp)
        for(int j[][] : i)
            for(int p[] : j)
                Arrays.fill(p, -1);
                 
    return solve(s, n, 0, k, (char)123, 0);
}
 
// Driver Code
public static void main(String args[])
{
    String S = "abbbcdcdd";
    int N = 9, K = 2;
     
    System.out.println(MinRunLengthEncoding(S, N, K));
}
}
 
// This code is contributed by hemanth gadarla
 
 

Python3




# Python3 program to implement
# the above approach
maxN = 20
 
dp = [[[[0 for i in range(maxN)]
           for j in range(27)]
           for k in range(27)]
           for l in range(maxN)]
 
# Function which solves the desired problem
def solve(s, n, idx, k, last, count):
     
    # idx: current index in s
    # k: Remaining number of deletions
    # last: Previous character
    # count: Number of occurrences
    # of the previous character
 
    # Base Case
    if (k < 0):
        return n + 1
 
    # If the entire string has
    # been traversed
    if (idx == n):
        return 0
 
    ans = dp[idx][k][ord(last) - ord('a')][count]
 
    # If precomputed subproblem
    # occurred
    if (ans != -1):
        return ans
 
    ans = n + 1
 
    # Minimum run length encoding by
    # removing the current character
    ans = min(ans, solve(s, n, idx + 1,
                         k - 1, last, count))
 
    # Minimum run length encoding by
    # retaining the current character
    inc = 0
 
    if (count == 1 or count == 9 or
        count == 99):
        inc = 1
 
    # If the current and the
    # previous characters match
    if (last == s[idx]):
        ans = min(ans, inc + solve(s, n, idx + 1, k,
                                   s[idx], count + 1))
 
    # Otherwise
    else:
        ans = max(ans, 1 + solve(s, n, idx + 1,
                                 k, s[idx], 1))
                                  
    dp[idx][k][ord(last) - ord('a')][count] = ans
    #print(ans)
     
    return dp[idx][k][ord(last) - ord('a')][count]
 
# Function to return minimum run-length encoding
# for string s by removing atmost k characters
def MinRunLengthEncoding(s, n, k):
     
    for i in range(maxN):
        for j in range(27):
            for k in range(27):
                for l in range(maxN):
                    dp[i][j][k][l] = -1
                     
    return solve(s, n, 0, k, chr(123), 0) - 1
 
# Driver Code
if __name__ == '__main__':
     
    S = "abbbcdcdd"
    N = 9
    K = 2
 
    print(MinRunLengthEncoding(S, N, K))
 
# This code is contributed by gauravrajput1
 
 

C#




// C# program to implement
// the above approach
using System;
class GFG{
 
static int maxN = 20;
 
static int [,,,]dp =
       new int[maxN, maxN,
               27, maxN];
 
// Function which solves
// the desired problem
public static int solve(String s, int n,
                        int idx, int k,
                        char last, int count)
{   
  // idx: current index in s
  // k: Remaining number of deletions
  // last: Previous character
  // count: Number of occurrences
  // of the previous character
 
  // Base Case
  if (k < 0)
    return n + 1;
 
  // If the entire string
  // has been traversed
  if (idx == n)
    return 0;
 
  int ans = dp[idx, k, last -
               'a', count];
 
  // If precomputed subproblem
  // occurred
  if (ans != -1)
    return ans;
 
  ans = n + 1;
 
  // Minimum run length encoding by
  // removing the current character
  ans = Math.Min(ans,
                 solve(s, n, idx + 1,
                       k - 1, last,
                       count));
 
  // Minimum run length encoding by
  // retaining the current character
  int inc = 0;
 
  if (count == 1 || count == 9 ||
      count == 99)
    inc = 1;
 
  // If the current and the
  // previous characters match
  if (last == s[idx])
  {
    ans = Math.Min(ans, inc +
                   solve(s, n, idx + 1,
                         k, s[idx],
                         count + 1));
  }
 
  // Otherwise
  else
  {
    ans = Math.Min(ans, 1 +
                   solve(s, n, idx + 1,
                         k, s[idx], 1));
  }
  return dp[idx, k, last -
            'a', count] = ans;
}
 
// Function to return minimum
// run-length encoding for string
// s by removing atmost k characters
public static int MinRunLengthEncoding(String s,
                                       int n, int k)
{
  for (int i = 0; i < maxN; i++)
    for (int j = 0; j < maxN; j++)
      for (int p = 0; p < 27; p++)
        for (int l = 0; l < maxN; l++)
          dp[i, j, p, l] = -1;
 
  return solve(s, n, 0,
               k, (char)123, 0);
}
 
// Driver Code
public static void Main(String []args)
{
  String S = "abbbcdcdd";
  int N = 9, K = 2;
  Console.WriteLine(
          MinRunLengthEncoding(S,
                               N, K));
}
}
 
// This code is contributed by 29AjayKumar
 
 

Javascript




<script>
 
    // JavaScript program to implement the above approach
     
    let maxN = 20;
  
    let dp = new Array(maxN);
 
    // Function which solves the desired problem
    function solve(s, n, idx, k, last, count)
    {
 
        // idx: current index in s
        // k: Remaining number of deletions
        // last: Previous character
        // count: Number of occurrences
        // of the previous character
 
        // Base Case
        if (k < 0)
            return n + 1;
 
        // If the entire string has
        // been traversed
        if (idx == n)
            return 0;
 
        let ans = dp[idx][k][last - 'a'.charCodeAt()][count];
 
        // If precomputed subproblem
        // occurred
        if (ans != -1)
            return ans;
 
        ans = n + 1;
 
        // Minimum run length encoding by
        // removing the current character
        ans = Math.min(ans, solve(s, n, idx + 1,
                                  k - 1, last,
                                  count));
 
        // Minimum run length encoding by
        // retaining the current character
        let inc = 0;
 
        if (count == 1 || count == 9 || count == 99)
            inc = 1;
 
        // If the current and the
        // previous characters match
        if (last == s[idx].charCodeAt())
        {
            ans = Math.min(ans, inc + solve(s, n, idx + 1,
                                            k, s[idx].charCodeAt(),
                                            count + 1));
        }
 
        // Otherwise
        else
        {
            ans = Math.min(ans, 1 + solve(s, n, idx + 1, k,
                                          s[idx].charCodeAt(), 1));
        }
        dp[idx][k][last - 'a'.charCodeAt()][count] = ans;
        return dp[idx][k][last - 'a'.charCodeAt()][count];
    }
 
    // Function to return minimum run-length encoding
    // for string s by removing atmost k characters
    function MinRunLengthEncoding(s, n, k)
    {
        for(let i = 0; i < maxN; i++)
        {
            dp[i] = new Array(maxN);
            for(let j = 0; j < maxN; j++)
            {
                dp[i][j] = new Array(27);
                for(let k = 0; k < 27; k++)
                {
                    dp[i][j][k] = new Array(maxN);
                    for(let l = 0; l < maxN; l++)
                    {
                        dp[i][j][k][l] = -1;
                    }
                }
            }
        }
 
        return solve(s, n, 0, k, 123, 0);
    }
     
    let S = "abbbcdcdd";
    let N = 9, K = 2;
      
    document.write(MinRunLengthEncoding(S, N, K));
     
</script>
 
 
Output: 
5

 

Time Complexity: O(26 * N2 * K)
Auxiliary Space: O(26 * N2 * K)



Next Article
Minimum operations required to convert all characters of a String to a given Character

S

shobhitgupta907
Improve
Article Tags :
  • C++ Programs
  • Combinatorial
  • Data Structures
  • DSA
  • Dynamic Programming
  • Recursion
  • Strings
  • frequency-counting
  • Memoization
  • Permutation and Combination
Practice Tags :
  • Combinatorial
  • Data Structures
  • Dynamic Programming
  • Recursion
  • Strings

Similar Reads

  • Minimum operations required to convert all characters of a String to a given Character
    Given string str, a character ch, and an integer K, the task is to find the minimum number of operations required to convert all the characters of string str to ch. Each operation involves converting K closest characters from each side of the index i, i.e., characters in the indices [i - K, i + K] c
    9 min read
  • Minimize count of flips required such that no substring of 0s have length exceeding K
    Given a binary string str of length N and an integer K where K is in the range (1 ? K ? N), the task is to find the minimum number of flips( conversion of 0s to 1 or vice versa) required to be performed on the given string such that the resulting string does not contain K or more zeros together. Exa
    6 min read
  • Count distinct substrings that contain some characters at most k times
    Given a integer k and a string str, the task is to count the number of distinct sub-strings such that each sub-string does not contain some specific characters more than k times. The specific characters are given as another string. Examples: Input: str = "ababab", anotherStr = "bcd", k = 1 Output: 5
    7 min read
  • Minimum number of alternate subsequences required to be removed to empty a Binary String
    Given a binary string S consisting of N characters, the task is to print the minimum number of operations required to remove all the characters from the given string S by removing a single character or removing any subsequence of alternate characters in each operation. Examples: Input: S = "010101"O
    6 min read
  • Reduce the string to minimum length with the given operation
    Given a string str consisting of lowercase and uppercase characters, the task is to find the minimum possible length the string can be reduced to after performing the given operation any number of times. In a single operation, any two consecutive characters can be removed if they represent the same
    6 min read
  • Minimum bit flips such that every K consecutive bits contain at least one set bit
    Given a binary string S, and an integer K, the task is to find the minimum number of flips required such that every substring of length K contains at least one '1'.Examples: Input: S = "10000001" K = 2 Output: 3 Explanation: We need only 3 changes in string S ( at position 2, 4 and 6 ) so that the s
    8 min read
  • Largest substring where all characters appear at least K times | Set 2
    Given a string str and an integer K, the task is to find the length of the longest sub-string S such that every character in S appears at least K times. Examples: Input: str = "aabbba", K = 3Output: 6 Explanation: In substring aabbba, each character repeats at least k times and its length is 6. Inpu
    7 min read
  • Reverse alternate k characters in a string
    Given a string str and an integer k, the task is to reverse alternate k characters of the given string. If characters present are less than k, leave them as it is.Examples: Input: str = "geeksforgeeks", k = 3 Output: eegksfgroeeksInput: str = "abcde", k = 2 Output: bacde Approach: The idea is to fir
    9 min read
  • Number of distinct words of size N with at most K contiguous vowels
    Given two integers n and k, count the number of distinct strings of length n of lowercase alphabets such that there are at most k consecutive vowels in any part of the string.Note: Since the result can be very large, output the answer modulo 1e9 + 7. Examples: Input: n = 1, k = 0Output: 21Explanatio
    15 min read
  • Smallest string which not a subsequence of the given string
    Given a string str, consisting of lowercase alphabets, the task is to find the shortest string which is not a subsequence of the given string. If multiple strings exist, then print any one of them. Examples: Input: str = "abaabcc" Output: d Explanation: One of the possible shortest string which is n
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences