Lexicographically smallest string with given string as prefix | Java program for the above approach ; Function to find the whether the string temp starts with str or not ; Base Case ; Check for the corresponding characters in temp & str ; Function to find lexicographic smallest string consisting of the string str as prefix ; Sort the given array string arr [ ] ; If the i - th string contains given string as a prefix , then print the result ; If no string exists then return " - 1" ; Driver Code
import java . util . Arrays ; class GFG { static boolean is_prefix ( String temp , String str ) { if ( temp . length ( ) < str . length ( ) ) return false ; else { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str . charAt ( i ) != temp . charAt ( i ) ) return false ; } return true ; } } static String lexicographicallyString ( String [ ] input , int n , String str ) { Arrays . sort ( input ) ; for ( int i = 0 ; i < n ; i ++ ) { String temp = input [ i ] ; if ( is_prefix ( temp , str ) ) { return temp ; } } return " - 1" ; } public static void main ( String args [ ] ) { String [ ] arr = { " apple " , " appe " , " apl " , " aapl " , " appax " } ; String S = " app " ; int N = 5 ; System . out . println ( lexicographicallyString ( arr , N , S ) ) ; } }