Lexicographically smallest string possible by merging two sorted strings | Function to find lexicographically smallest string possible by merging two sorted strings ; Stores length of string s1 ; Stores length of string s2 ; Pointer to beginning of string1 i . e . , s1 ; Pointer to beginning of string2 i . e . , s2 ; Stores the final string ; Traverse the strings ; Append the smaller of the two current characters ; Append the remaining characters of any of the two strings ; Print the final string ; Driver Code ; Function Call
function mergeStrings ( s1 , s2 ) { var len1 = s1 . length ; var len2 = s2 . length ; var pntr1 = 0 ; var pntr2 = 0 ; var ans = " " ; while ( pntr1 < len1 && pntr2 < len2 ) { if ( s1 [ pntr1 ] < s2 [ pntr2 ] ) { ans += s1 [ pntr1 ] ; pntr1 ++ ; } else { ans += s2 [ pntr2 ] ; pntr2 ++ ; } } if ( pntr1 < len1 ) { ans += s1 . substr ( pntr1 , len1 ) ; } if ( pntr2 < len2 ) { ans += s2 . substr ( pntr2 , len2 ) ; } document . write ( ans ) ; } var S1 = " " ; var S2 = " " ; mergeStrings ( S1 , S2 ) ;