text: Lexicographically smallest string with given string as prefix | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool is_prefix ( string temp , string str ) { if ( temp . length ( ) < str . length ( ) ) return 0 ; else { for ( int i = 0 ; i < str . length ( ) ; i ++ ) { if ( str [ i ] != temp [ i ] ) return 0 ; } return 1 ; } } string lexicographicallyString ( string input [ ] , int n , string str ) { sort ( input , input + n ) ; for ( int i = 0 ; i < n ; i ++ ) { string temp = input [ i ] ; if ( is_prefix ( temp , str ) ) { return temp ; } } return " - 1" ; } int main ( ) { string arr [ ] = { " apple " , " appe " , " apl " , " aapl " , " appax " } ; string S = " app " ; int N = 5 ; cout << lexicographicallyString ( arr , N , S ) ; return 0 ; }