Reverse individual words with O ( 1 ) extra space | Javascript implementation of the approach ; Function to resturn the string after reversing the individual words ; Pointer to the first character of the first word ; If the current word has ended ; Pointer to the last character of the current word ; Reverse the current word ; Pointer to the first character of the next word ; Driver code
function swap ( str , i , j ) { let sb = str . split ( " " ) ; sb [ i ] = str [ j ] ; sb [ j ] = str [ i ] ; return sb . join ( " " ) ; } function reverseWords ( str ) { let start = 0 ; for ( let i = 0 ; i < str . length ; i ++ ) { if ( str [ i ] == ' ' i == str . length - 1 ) { let end ; if ( i == str . length - 1 ) end = i ; else end = i - 1 ; while ( start < end ) { str = swap ( str , start , end ) ; start ++ ; end -- ; } start = i + 1 ; } } return str ; } let str = " " ; document . write ( reverseWords ( str ) ) ;