Skip to content
Related Articles

Related Articles

Improve Article

Lexicographically smallest string with given string as prefix

  • Last Updated : 07 Oct, 2021
Geek Week

Given an array arr[] consisting of N strings and a string S if size M, the task is to find the lexicographically smallest string consisting of the string S as the prefix. If there doesn’t exist any string starting with prefix S then print “-1”.

Examples:

Input: arr[] = {“apple”, “appe”, “apl”, “aapl”, “appax”}, S = “app”
Output: appax
Explanation:
The lexicographical order of the strings consisting of “app” as the substring is {“aapl”, “apl”, “appax”, “appe”, “apple”}. The smallest lexicographic string containing is “appax”.

Input: arr[] = {“can”, “man”, “va”}, S = “van”
Output: -1

Approach: The given problem can be solved by sorting the given array of strings arr[] such that all the strings starting with prefixes S occur consecutively. Now traverse the given array of strings arr[] and when the first string whose prefix matches with S then print that string and break out of the loop. Otherwise, print “-1”.



Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the whether the
// string temp starts with str or not
bool is_prefix(string temp, string str)
{
    // Base Case
    if (temp.length() < str.length())
        return 0;
    else {
 
        // Check for the corresponding
        // characters in temp & str
        for (int i = 0;
             i < str.length(); i++) {
 
            if (str[i] != temp[i])
                return 0;
        }
        return 1;
    }
}
 
// Function to find lexicographic smallest
// string consisting of the string str
// as prefix
string lexicographicallyString(
    string input[], int n, string str)
{
    // Sort the given array string arr[]
    sort(input, input + n);
 
    for (int i = 0; i < n; i++) {
        string temp = input[i];
 
        // If the i-th string contains
        // given string as a prefix,
        // then print the result
        if (is_prefix(temp, str)) {
            return temp;
        }
    }
 
    // If no string exists then
    // return "-1"
    return "-1";
}
 
// Driver Code
int main()
{
    string arr[] = { "apple", "appe", "apl",
                     "aapl", "appax" };
    string S = "app";
    int N = 5;
 
    cout << lexicographicallyString(
        arr, N, S);
 
    return 0;
}

Java




// Java program for the above approach
 
import java.util.Arrays;  
 
class GFG {
 
    // Function to find the whether the
    // string temp starts with str or not
    static boolean is_prefix(String temp, String str)
    {
        // Base Case
        if (temp.length() < str.length())
            return false;
        else {
 
            // Check for the corresponding
            // characters in temp & str
            for (int i = 0; i < str.length(); i++) {
 
                if (str.charAt(i) != temp.charAt(i))
                    return false;
            }
            return true;
        }
    }
 
    // Function to find lexicographic smallest
    // string consisting of the string str
    // as prefix
    static String lexicographicallyString(String[] input,
                                          int n, String str)
    {
        // Sort the given array string arr[]
        Arrays.sort(input);
 
        for (int i = 0; i < n; i++) {
            String temp = input[i];
 
            // If the i-th string contains
            // given string as a prefix,
            // then print the result
            if (is_prefix(temp, str)) {
                return temp;
            }
        }
 
        // If no string exists then
        // return "-1"
        return "-1";
    }
 
    // Driver Code
    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));
    }
}
 
// This code is contributed by AnkThon

Python3




# Python 3 program for the above approach
 
# Function to find the whether the
# string temp starts with str or not
def is_prefix(temp, str):
   
    # Base Case
    if (len(temp) < len(str)):
        return 0
    else:
 
        # Check for the corresponding
        # characters in temp & str
        for i in range(len(str)):
            if (str[i] != temp[i]):
                return 0
        return 1
 
# Function to find lexicographic smallest
# string consisting of the string str
# as prefix
def lexicographicallyString(input, n, str):
   
    # Sort the given array string arr[]
    input.sort()
 
    for i in range(n):
        temp = input[i]
 
        # If the i-th string contains
        # given string as a prefix,
        # then print the result
        if (is_prefix(temp, str)):
            return temp
 
    # If no string exists then
    # return "-1"
    return "-1"
 
# Driver Code
if __name__ == '__main__':
    arr = ["apple", "appe", "apl", "aapl", "appax"]
    S = "app"
    N = 5
 
    print(lexicographicallyString(arr, N, S))
 
    # This code is contributed by ipg2016107.

C#




// C# program for the above approach
using System;
class GFG {
 
    // Function to find the whether the
    // string temp starts with str or not
    static bool is_prefix(string temp, string str)
    {
        // Base Case
        if (temp.Length < str.Length)
            return false;
        else {
 
            // Check for the corresponding
            // characters in temp & str
            for (int i = 0; i < str.Length; i++) {
 
                if (str[i] != temp[i])
                    return false;
            }
            return true;
        }
    }
 
    // Function to find lexicographic smallest
    // string consisting of the string str
    // as prefix
    static string lexicographicallyString(string[] input,
                                          int n, string str)
    {
        // Sort the given array string arr[]
        Array.Sort(input);
 
        for (int i = 0; i < n; i++) {
            string temp = input[i];
 
            // If the i-th string contains
            // given string as a prefix,
            // then print the result
            if (is_prefix(temp, str)) {
                return temp;
            }
        }
 
        // If no string exists then
        // return "-1"
        return "-1";
    }
 
    // Driver Code
    public static void Main()
    {
        string[] arr
            = { "apple", "appe", "apl", "aapl", "appax" };
        string S = "app";
        int N = 5;
 
        Console.WriteLine(
            lexicographicallyString(arr, N, S));
    }
}
 
// This code is contributed by ukasp.

Javascript




<script>
        // JavaScript Program to implement
        // the above approach
 
        // Function to find the whether the
        // string temp starts with str or not
        function is_prefix(temp, str)
        {
         
            // Base Case
            if (temp.length < str.length)
                return 0;
            else {
 
                // Check for the corresponding
                // characters in temp & str
                for (let i = 0;
                    i < str.length; i++) {
 
                    if (str[i] != temp[i])
                        return 0;
                }
                return 1;
            }
        }
 
        // Function to find lexicographic smallest
        // string consisting of the string str
        // as prefix
        function lexicographicallyString(
            input, n, str)
       {
        
            // Sort the given array string arr[]
            input = Array.from(input).sort();
            for (let i = 0; i < n; i++) {
                let temp = input[i];
 
                // If the i-th string contains
                // given string as a prefix,
                // then print the result
                if (is_prefix(temp, str)) {
                    return temp;
                }
            }
 
            // If no string exists then
            // return "-1"
            return "-1";
        }
 
        // Driver Code
        let arr = ["apple", "appe", "apl",
            "aapl", "appax"];
        let S = "app";
        let N = 5;
 
        document.write(lexicographicallyString(
            arr, N, S));
 
// This code is contributed by Potta Lokesh
    </script>
Output: 
appax

 

Time Complexity: O(M*K*N*log N), where K is the maximum length of the string in the array arr[].
Auxiliary Space: O(N)

Another Approach: The above approach can also be optimized by using the Trie Data Structure by inserting all the given strings in the Trie and then check for the first string that exists in the Trie having prefix S.

Time Complexity: O(M*N)
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :