Lexicographically smallest string with given string as prefix
Last Updated :
07 Oct, 2021
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>
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)
Similar Reads
K-th lexicographically smallest unique substring of a given string Given a string S. The task is to print the K-th lexicographically the smallest one among the different substrings of s.A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z, and an empty stri
5 min read
Find Lexicographically smallest String with Prefix Reversal Given a string str of length N. You have to choose a non-zero integer K (K <= N), such that in one operation you can take the prefix of the string of length K and append the reverse of it to itself, the task is to find the lexicographically smallest string you can get. Examples: Input: str = "bvd
5 min read
Lexicographically smallest string which is not a subsequence of given string Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a
5 min read
Lexicographically smallest string possible by using given operations Given a string S consisting of digits from 0 to 9 inclusive, the task is to form the lexicographically smallest string by performing an operation any number of times. In one operation you can choose any position i and delete the digit d at s[i] and insert min(d+1, 9) on any position (at the beginnin
7 min read
Lexicographically smallest String by pair swapping Suppose you are given a string Str of length N and a set of Pairs ( i, j such that 0 <= i < j < N, 0 based indexing). Pair âi, jâ means that you can swap the ith and jth characters in the string any number of times. You have to output the lexicographically smallest string that can be produc
11 min read