Replace all occurrences of string AB with C without using extra space | Efficient javascript program to replace all occurrences of " AB " with " C " ; Index in modified string ; Index in original string ; Traverse string ; Replace occurrence of " AB " with " C " ; Increment j by 2 ; Add a null character to terminate string ; Driver code
function translate ( str ) { var len = str . length ; if ( len < 2 ) return ; var i = 0 ; var j = 0 ; while ( j < len - 1 ) { if ( str [ j ] == ' ' && str [ j + 1 ] == ' ' ) { j = j + 2 ; let firstPart = str . substr ( 0 , i ) ; let lastPart = str . substr ( i + 1 ) ; str = firstPart + ' ' + lastPart ; i += 1 ; continue ; } let firstPart = str . substr ( 0 , i ) ; let lastPart = str . substr ( i + 1 ) ; str = firstPart + str [ j ] + lastPart ; i += 1 ; j += 1 ; } if ( j == len - 1 ) { let firstPart = str . substr ( 0 , i ) ; let lastPart = str . substr ( i + 1 ) ; str = firstPart + str [ j ] + lastPart ; i += 1 ; } let firstPart = str . substr ( 0 , i ) ; let lastPart = str . substr ( i + 1 ) ; str = firstPart + ' ' + lastPart ; firstPart = str . substr ( 0 , len - 1 ) ; lastPart = str . substr ( len ) ; str = firstPart + ' ' + lastPart ; str [ len - 1 ] = ' ' ; return str ; } var str = " " ; document . write ( " " + " " + translate ( str ) ) ;