Need to update the solution
Please read the question completely before going through the solution
This video clearly explains a two pointer approach to solve the problem
It starts with initialising the first pointer , second pointer at index 0 of array and then for each of char (ie the char at first pointer) second pointer is moved till we find a mismatch in characters at first and second pointer.
index variable is used to track the current position of updated character array , after each char entry index is forwarded to next position , and the count entry of count j-i is done only when count is more than 1 .
/**
* @param {character[]} chars
* @return {number}
*/
var compress = function(chars) {
let index = 0;
let i = 0;
let j = 0;
while(i<chars.length){
j=i;
while(j<chars.length && chars[i] === chars[j]){
j++
}
chars[index++] = chars[i];
let count = (j - i) ;
if (count > 1) {
let str = count.toString(); // Convert count to string
for (let digit of str) {
chars[index++] = digit;
}
}
i=j;
}
return index
};
/**
* @param {character[]} chars
* @return {number}
*/
var compress = function(chars) {
let n = chars.length;
if (n <= 1) {
return n; // For arrays of length 0 or 1, no compression needed
}
let index = 0; // Position in the compressed array
let counter = 1;
for (let i = 1; i <= n; i++) {
if (chars[i] === chars[i - 1]) {
counter++;
} else {
// Place the character at the current index
chars[index++] = chars[i - 1];
// Place the count if it's greater than 1
if (counter > 1) {
for (let digit of counter.toString()) {
chars[index++] = digit;
}
}
// Reset counter
counter = 1;
}
}
return index; // Length of the compressed array
};
Syntax Learnings
- index++ is a post increment operator , it first assign the value and then increments
- num can be converted to string by .toString() method
Top comments (0)