Move spaces to front of string in single traversal | Function to find spaces and move to beginning ; Keep copying non - space characters ; Move spaces to be beginning ; Driver code
function moveSpaceInFront ( str ) { var i = str . length - 1 ; for ( var j = i ; j >= 0 ; j -- ) if ( str [ j ] !== " " ) str [ i -- ] = str [ j ] ; while ( i >= 0 ) str [ i -- ] = " " ; } var str = " " . split ( " " ) ; moveSpaceInFront ( str ) ; document . write ( str . join ( " " ) ) ;