# The shortest possible length of a compressed string

*Edit: This is a variant of the original question, in which instead of removing K number of characters we replace them with any character.*

Let’s have a look at the task description:

The task is to compress a string by replacing any number of characters, so that the compressed version of it is the shortest possible. Example of compression: “GGGGG” -> “5G”, the number before a letter denotes how many occurences of it are in a given string.

- “XS” -> “XS” – it’s not possible to compress it further, plus adding a 1 in before the letters would make it even longer
- “BCCCDDEEDDD” -> “B3C2D2E3D”
- “ZZZZZZZZZZZATTZZZZZZZZZZ” -> “11ZA2T10Z”
In the third example if we were able to replace the “ATT” part, the whole string would be compressed to “24Z”. So now we can provide a K – number, which would refer to the maximum number of characters in a string, which could be replaced to obtain the shortest compressed string possible.

```
class Solution {
public int solution(String S, int K)
{
}
}
```

that given a string S of length N and an integer K, returns the shortest possible length of the compressed representation of S after removing exactly K characters from S.

Example:

Given S = “AAAAAAAAAAABXXAAAAAAAAAA” and K=3, the function should return 3, because after removing “BXX” from S, we are left with “AAAAAAAAAAAAAAAAAAAAA”, which compresses to a representation of length 3 – “21A”.

Requirement:

```
N is an integer within the range [1...100,000];
K is an integer within the range [0...100,000];
K <= N;
string S consists only of uppercase letters (A-Z)
```

First of all, I would prefer to avoid starting a discussion on whether or not such tests are good measurement for programming skills. Leaving all doubts aside, the truth is if you want to land a job at one of the top companies, you have to practice a lot, even though writing moderately difficult algorithms probably won’t be a part of your daily routine.

So how to approach this task? I usually start by looking at the boundary conditions:

```
N is an integer within the range [1...100,000];
K is an integer within the range [0...100,000];
K <= N;
string S consists only of uppercase letters (A-Z)
```

Ok, we don’t have to consider case sensitivity in char comparisons, fair enough. We may also notice that when given string is less than 3 characters, the result is always going to be equal to its length:

original | compressed | result |

“” | “” | 0 |

a | a | 1 |

ab | ab | 2 |

bb | 2b | 2 |

Another thing worth noticing is that when K is equal or 1 less than the string length, the result will be equal to the length of the string expressed as a string + 1:

original | k | compressed | result |

aaaaa | 0 | 5a | 2 |

abcde | 4 | 5a | 2 |

abcdefghij | 10 | 10a | 3 |

abcdefghijk | 10 | 11a | 3 |

So we start with:

```
public static int findCompressedLength(string S, int K)
{
if (S.Length < 3)
return S.Count();
else if (K >= S.Count()-1)
return S.Count().ToString().Length + 1;
}
```

Boundary cases are done, so now we can focus on the main problem. First, we need to find such permutation of letters, where the sequence of the repeating char is the longest. Possibly we could use a basic brute force solution here with the O(N*K) complexity to calculate K long ranges for all N letters in the string, however, this would surely fail the codility performance criteria. There’s another approach to this type of problems called sliding window or moving window with linear complexity.

How does it work? You start by using two pointers (current position of the char in string and the window start). Then with each loop, you store the char along with its current frequency in a dictionary or hashmap.

`if (charsWithFrequencies.ContainsKey(S[i]))`

` charsWithFrequencies[S[i]]++;`

`else`

` charsWithFrequencies.Add(S[i], 1);`

`repetitions = charsWithFrequencies[S[i]];`

Then you add a condition which checks of the distance from current index to the beginning of the window – number of the current letter repetitions + 1 (because length is denoted in 0 based convention) is bigger than the number of allowed letter replacement (K). Please take your time to wrap your mind around it.

`if (i - windowStart - repetitions + 1 > K)`

`{`

` charsWithFrequencies[S[windowStart]]--;`

` windowStart++;`

`}`

If so, you move the window forward and decrease the frequency of the letter, which was placed in a string and the window beginning index.

Great, half of the task is done already. Now, since we know that the algorithm is going to return the longest sequence, each time it’s saving this sequence, let’s save few more properties:

```
if (i - windowStart + 1 > longestSequence)
{
longestSequence = i - windowStart + 1;
longestSequenceInstance.EndingIndex = i;
longestSequenceInstance.StartingIndex = i - longestSequence + 1;
longestSequenceInstance.Letter = S[i];
longestSequenceInstance.Occurences = longestSequence;
}
```

I’ve created a simple struct just for legibility, in which we’ll store the letter with the longest sequence, it’s ending and starting indiced and the number of occurences:

```
public struct longestSequenceInstance
{
public char Letter { get; set; }
public int EndingIndex { get; set; }
public int StartingIndex { get; set; }
public int Occurences { get; set; }
}
```

The rest is quite simple, we replace part of the original string with the longest subsequence:

```
var workingString = new StringBuilder(S);
var replaced = workingString.Remove(longestSequenceInstance.StartingIndex, longestSequenceInstance.Occurences - 1)
.Insert(longestSequenceInstance.StartingIndex, String.Concat(Enumerable.Repeat(longestSequenceInstance.Letter, longestSequenceInstance.Occurences-1)))
.ToString();
```

```
int occurences = 1;
char currentChar;
var strBuilder = new StringBuilder("");
for (var i = 1; i < replaced.Length; i++)
{
currentChar = replaced[i];
if (replaced[i - 1] == replaced[i])
occurences++;
else
{
if (occurences > 1)
strBuilder.Append(occurences);
strBuilder.Append(replaced[i - 1]);
occurences = 1;
}
if (i == replaced.Length - 1)
{
if (occurences > 1)
strBuilder.Append(occurences);
strBuilder.Append(currentChar);
}
}
var stringFinal = strBuilder.ToString();
return stringFinal.Count();
```

Calculation complexity equals to O(N) + O(1) + O(N). Space complexity equals to 2N + 2logN.

Here’s the full listing (C#). Please let me know in comments if you found a more efficient way of solving this task.

```
public static int findCompressedLength(string S, int K)
{
if (S.Length < 3)
return S.Count();
else if (K >= S.Count()-1)
return S.Count().ToString().Length + 1;
Dictionary<char, int> charsWithFrequencies = new Dictionary<char, int>();
var windowStart = 0;
int longestSequence = 0;
var repetitions = 0;
var longestSequenceInstance = new longestSequenceInstance();
for (var i = 0; i < S.Length; i++)
{
if (charsWithFrequencies.ContainsKey(S[i]))
charsWithFrequencies[S[i]]++;
else
charsWithFrequencies.Add(S[i], 1);
repetitions = charsWithFrequencies[S[i]];
if (i - windowStart - repetitions + 1 > K)
{
charsWithFrequencies[S[windowStart]]--;
windowStart++;
}
if (i - windowStart + 1 > longestSequence)
{
longestSequence = i - windowStart + 1;
longestSequenceInstance.EndingIndex = i;
longestSequenceInstance.StartingIndex = i - longestSequence + 1;
longestSequenceInstance.Letter = S[i];
longestSequenceInstance.Occurences = longestSequence;
}
}
var workingString = new StringBuilder(S);
var replaced = workingString.Remove(longestSequenceInstance.StartingIndex, longestSequenceInstance.Occurences - 1)
.Insert(longestSequenceInstance.StartingIndex, String.Concat(Enumerable.Repeat(longestSequenceInstance.Letter, longestSequenceInstance.Occurences-1)))
.ToString();
int occurences = 1;
char currentChar;
var strBuilder = new StringBuilder("");
for (var i = 1; i < replaced.Length; i++)
{
currentChar = replaced[i];
if (replaced[i - 1] == replaced[i])
occurences++;
else
{
if (occurences > 1)
strBuilder.Append(occurences);
strBuilder.Append(replaced[i - 1]);
occurences = 1;
}
if (i == replaced.Length - 1)
{
if (occurences > 1)
strBuilder.Append(occurences);
strBuilder.Append(currentChar);
}
}
var stringFinal = strBuilder.ToString();
return stringFinal.Count();
}
}
public struct longestSequenceInstance
{
public char Letter { get; set; }
public int EndingIndex { get; set; }
public int StartingIndex { get; set; }
public int Occurences { get; set; }
}
```