Here I have created a program for string compression, so for input chars = ["a","a","b","b","c","c","c"] we are getting output like 6 characters ["a","2","b","2","c","3"]. So I have created a program using the array approach, which is very lengthy and complex too. Is there any solution using the two-pointer or recursion approach to solve that program with very little code and efficiency? Can you please provide that with very short code? The code is given below.
var compress = function(chars) {
if (!chars.length) {
return 0;
}
let j = 0;
let cur = chars[0];
let counter = 0;
for (let i = 0; i <= chars.length; i++) {
if (chars[i] === cur) {
counter++;
} else {
// Otherwise, add the current character and count to the compressed array
chars[j] = cur;
if (counter > 1) {
const s = counter.toString();
for (let k = 0; k < s.length; k++) {
chars[++j] = s[k];
}
}
j++;
cur = chars[i];
counter = 1;
}
}
return j
};
console.log(compress ('aaaabbc'))//a4b2c
3
Answers
You can use a two-pointer approach to achieve the string compression with a more concise code. Here’s a shorter version of your program:
Slightly modified two-pointer approach to avoid counter increments.
I have labeled the variables so you can follow the code easily.
Hope you will find this useful.
Here is the solution using two pointers. Key concept here is: DO NOT PASS TWINCE FOR EACH ELEMENT IN THE INPUT.
Complexity: