Good evening! Here's our prompt for today.
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:
SNIPPET
1s: 2
2t: 3
3r: 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:
SNIPPET
1compactLength('aabbbbbbbbbbbbb')
2// 5 because we end up with `a2b13`
Another to consider:
SNIPPET
1compactLength('s')
2// 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)
Try to solve this here or in Interactive Mode.
How do I practice this challenge?
xxxxxxxxxx
47
console.log('PASSED: ' + "compactLength('aabbbbbbbbbbbbb') should return 5");
var assert = require('assert');
​
/**
* @param {character[]} str
* @return {number}
*/
function compactLength(str) {
// fill this in
return str.length;
}
​
try {
assertIsFunction(compactLength, 'compactLength is a function');
​
console.log('PASSED: ' + '`compactLength` is a function');
} catch (err) {
console.log(err);
}
​
try {
assert.equal(compactLength('a'), 1);
​
console.log('PASSED: ' + "compactLength('a') should return 1");
} catch (err) {
console.log(err);
}
​
try {
assert.equal(compactLength('abb'), 3);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Here's how we would solve this problem...
How do I use this guide?