Lexicographically smallest string possible by merging two sorted strings | Java program for the above approach ; 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
import java . io . * ; class GFG { static void mergeStrings ( String s1 , String s2 ) { int len1 = s1 . length ( ) ; int len2 = s2 . length ( ) ; int pntr1 = 0 ; int pntr2 = 0 ; String ans = " " ; while ( pntr1 < len1 && pntr2 < len2 ) { if ( s1 . charAt ( pntr1 ) < s2 . charAt ( pntr2 ) ) { ans += s1 . charAt ( pntr1 ) ; pntr1 ++ ; } else { ans += s2 . charAt ( pntr2 ) ; pntr2 ++ ; } } if ( pntr1 < len1 ) { ans += s1 . substring ( pntr1 , len1 ) ; } if ( pntr2 < len2 ) { ans += s2 . substring ( pntr2 , len2 ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { String S1 = " abdcdtx " ; String S2 = " achilp " ; mergeStrings ( S1 , S2 ) ; } }