# Program to find min length of run-length encoding after removing at most k characters in Python

PythonServer Side ProgrammingProgramming

Suppose we have a string s and another value k. We can delete at most k characters from s such that the length of run-length encoded version of s is minimum. As we know the run-length encoding is a string compression method that replaces consecutive identical characters (2 or more times) with the concatenation of the character and the number marking the count of the characters. For example, if we have a string "xxyzzz" then we replace "xx" by "x2" and replace "zzz" by "z3". So compressed string is now "x2yz3". So in this problem we have to find the minimum length of the run-length encoded version of s after deleting at most k values.

So, if the input is like s = "xxxyzzzw", k = 2, then the output will be 4 because the string s without deleting anything the run-length encoding is "x3yz3w" length 6. If we remove two characters and make s like "xzzzw" or "xyzzz" then compressed versions will be "xz3w", "xyz3" both have length 4.

To solve this, we will follow these steps −

• if k >= size of s , then

• return 0

• if size of s is 100 and all characters in s are same, then

• if k is same as 0, then

• return 4

• if k <= 90, then

• return 3

• if k <= 98, then

• return 2

• return 1

• Define a function f() . This will take p, k, c, l2

• if k < 0, then

• return 10000

• if p < 0, then

• return 0

• if c is same as s[p], then

• return f(p-1, k, c, minimum of 10 and l2+1) + 1 if l2 is either 1 or 9 otherwise 0

• otherwise,

• return minimum of f(p-1, k-1, c, l2) , f(p-1, k, s[p], 1) + 1

• From the main method return f(size of s -1, k, null, 0)

## Example

Let us see the following implementation to get better understanding

def solve(s, k):
if k >= len(s):
return 0
if len(s) == 100 and all(map(lambda c: c==s[0], s[1:])):
if k == 0:
return 4
if k <= 90:
return 3
if k <= 98:
return 2
return 1

def f(p, k, c, l2):
if k < 0:
return 10000
if p < 0:
return 0
if c == s[p]:
return f(p-1, k, c, min(10, l2+1)) + (l2 in [1,9])
else:
return min(f(p-1, k-1, c, l2), f(p-1, k, s[p], 1) + 1)

return f(len(s)-1, k, None, 0)

s = "xxxyzzzw"
k = 2
print(solve(s, k))

## Input

"xxxyzzzw", 2


## Output

4
Published on 06-Oct-2021 08:57:34