Length of String Compression
Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.
Description
Let's define the "compacting" of a string as taking an input like the following: 'sstttrrrr'.
We want to take the number of sequential appearances (number of times it shows up in a row) of each letter:
s: 2
t: 3
r: 4
And denote them next to the original character in the string, getting rid of the duplicates. In our above example, our output is: 's2t3r4'.
How long is this compacted string? Could you write a method that takes in a string and returns the length of the compacted one? Could you solve it using only O(1) extra space?

Here are few other examples:
compactLength('aabbbbbbbbbbbbb')
// 5 because we end up with `a2b13`
Another to consider:
compactLength('s')
// 1 because we still end up with just `s`
Constraints
- Length of the given string <=
100000 - The string comprises of ASCII characters
- Expected time complexity :
O(n) - Expected space complexity :
O(1)
CONTINUE WITH ALGODAILY PREMIUM
Keep going with the complete tutorial.
Unlock the remaining explanations and exercises, alongside the full learning library.
Explore Premium →