Reduce the string by removing K consecutive identical characters | Javascript implementation of the approach ; Function to find the reduced string ; Base Case ; Creating a stack of type Pair ; Length of the string S ; iterate through the string ; if stack is empty then simply add the character with count 1 else check if character is same as top of stack ; if character at top of stack is same as current character increase the number of repetitions in the top of stack by 1 ; if character at top of stack is not same as current character push the character along with count 1 into the top of stack ; iterate through the stack Use string ( int , char ) in order to replicate the character multiple times and convert into string then add in front of output string ; Driver code
class Pair { constructor ( c , ctr ) { this . c = c ; this . ctr = ctr ; } } function reduced_String ( k , s ) { if ( k == 1 ) { let ans = " " ; return ans ; } let st = [ ] ; let l = s . length ; let ctr = 0 ; for ( let i = 0 ; i < l ; i ++ ) { if ( st . length == 0 ) { st . push ( new Pair ( s [ i ] , 1 ) ) ; continue ; } if ( st [ st . length - 1 ] . c == s [ i ] ) { let p = st [ st . length - 1 ] ; st . pop ( ) ; p . ctr += 1 ; if ( p . ctr == k ) { continue ; } else { st . push ( p ) ; } } else { st . push ( new Pair ( s [ i ] , 1 ) ) ; } } let ans = " " ; while ( st . length > 0 ) { let c = st [ st . length - 1 ] . c ; let cnt = st [ st . length - 1 ] . ctr ; while ( cnt -- > 0 ) ans = c + ans ; st . pop ( ) ; } return ans ; } let k = 2 ; let st = " " ; let ans = reduced_String ( k , st ) ; document . write ( ans + " " ) ;