Lexicographically smallest subsequence possible by removing a character from given string - GeeksforGeeks

19 Feb, 2022
Given a string S of length N, the task is to find the lexicographically smallest subsequence of length (N – 1), i.e. by removing a single character from the given string.
Examples:
Input: S = “geeksforgeeks”Output: “eeksforgeeks”Explanation: Lexicographically smallest subsequence possible is “eeksforgeeks”.
Input: S = “zxvsjas”Output: “xvsjas”Explanation: Lexicographically smallest subsequence possible is “xvsjas”.
Naive Approach: The simplest approach is to generate all possible subsequences of length (N – 1) from the given string and store all subsequences in an array. Now, sort the array and print the string at 0th position for the smallest lexicographically subsequence.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the lexicographically// smallest subsequence of length N-1void firstSubsequence(string s){    vector<string> allsubseq;     string k;     // Generate all subsequence of    // length N-1    for (int i = 0; i < s.length(); i++) {         // Store main value of string str        k = s;         // Erasing element at position i        k.erase(i, 1);        allsubseq.push_back(k);    }     // Sort the vector    sort(allsubseq.begin(),         allsubseq.end());     // Print first element of vector    cout << allsubseq[0];} // Driver Codeint main(){    // Given string S    string S = "geeksforgeeks";     // Function Call    firstSubsequence(S);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){    Vector<String> allsubseq = new Vector<>();         // Generate all subsequence of    // length N-1    for(int i = 0; i < s.length(); i++)    {        String k = "";                 // Store main value of String str        for(int j = 0; j < s.length(); j++)        {            if (i != j)            {                k += s.charAt(j);            }        }        allsubseq.add(k);    }     // Sort the vector    Collections.sort(allsubseq);     // Print first element of vector    System.out.print(allsubseq.get(0));} // Driver Codepublic static void main(String[] args){         // Given String S    String S = "geeksforgeeks";     // Function Call    firstSubsequence(S);}} // This code is contributed by Amit Katiyar
# Python3 program for the above approach # Function to find the lexicographically# smallest subsequence of length N-1def firstSubsequence(s):     allsubseq = []     k = []     # Generate all subsequence of    # length N-1    for i in range(len(s)):         # Store main value of string str        k = [i for i in s]         # Erasing element at position i        del k[i]        allsubseq.append("".join(k))     # Sort the vector    allsubseq = sorted(allsubseq)     # Print first element of vector    print(allsubseq[0]) # Driver Codeif __name__ == '__main__':         # Given string S    S = "geeksforgeeks"     # Function Call    firstSubsequence(S) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(string s){    List<string> allsubseq = new List<string>();         // Generate all subsequence of    // length N-1    for(int i = 0; i < s.Length; i++)    {        string k = "";                 // Store main value of string str        for(int j = 0; j < s.Length; j++)        {            if (i != j)            {                k += s[j];            }        }        allsubseq.Add(k);    }     // Sort the vector    allsubseq.Sort();     // Print first element of vector    Console.WriteLine(allsubseq[0]);} // Driver Codepublic static void Main(){         // Given string S    string S = "geeksforgeeks";     // Function Call    firstSubsequence(S);}} // This code is contributed by ipg2016107
<script>// Javascript program for the above approach // Function to find the lexicographically// smallest subsequence of length N-1function firstSubsequence(s){    let allsubseq = [];          // Generate all subsequence of    // length N-1    for(let i = 0; i < s.length; i++)    {        let k = "";                  // Store main value of String str        for(let j = 0; j < s.length; j++)        {            if (i != j)            {                k += s[j];            }        }        allsubseq.push(k);    }      // Sort the vector    (allsubseq).sort();      // Print first element of vector    document.write(allsubseq[0]);} // Driver Code // Given String Slet S = "geeksforgeeks"; // Function CallfirstSubsequence(S);  // This code is contributed by patel2127</script>
Output:
eeksforgeeks
Time Complexity: O(N *N)Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to iterate over the string and check if the ith character is greater that (i + 1)th character, then simply remove the ith character and print the remaining string. Otherwise, remove the last element and print the desired subsequence.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the lexicographically// smallest subsequence of length N-1void firstSubsequence(string s){    // Store index of character    // to be deleted    int isMax = -1;     // Traverse the string    for (int i = 0;         i < s.length() - 1; i++) {         // If ith character > (i + 1)th        // character then store it        if (s[i] > s[i + 1]) {            isMax = i;            break;        }    }     // If any character found in non    // alphabetical order then remove it    if (isMax >= 0) {        s.erase(isMax, 1);    }     // Otherwise remove last character    else {        s.erase(s.length() - 1, 1);    }     // Print the resultant subsequence    cout << s;} // Driver Codeint main(){    // Given string S    string S = "geeksforgeeks";     // Function Call    firstSubsequence(S);     return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){         // Store index of character    // to be deleted    int isMax = -1;     // Traverse the String    for(int i = 0; i < s.length() - 1; i++)    {                 // If ith character > (i + 1)th        // character then store it        if (s.charAt(i) > s.charAt(i + 1))        {            isMax = i;            break;        }    }     // If any character found in non    // alphabetical order then remove it    if (isMax >= 0)    {        s = s.substring(0, isMax) +            s.substring(isMax + 1);        // s.rerase(isMax, 1);    }     // Otherwise remove last character    else    {        //s.erase(s.length() - 1, 1);        s = s.substring(0, s.length() - 1);             }     // Print the resultant subsequence    System.out.print(s);} // Driver Codepublic static void main(String[] args){         // Given String S    String S = "geeksforgeeks";     // Function Call    firstSubsequence(S);}} // This code is contributed by Princi Singh
# Python3 program for the above approach # Function to find the lexicographically# smallest subsequence of length N-1def firstSubsequence(s):     # Store index of character    # to be deleted    isMax = -1     # Traverse the String    for i in range(len(s)):         # If ith character > (i + 1)th        # character then store it        if (s[i] > s[i + 1]):            isMax = i            break     # If any character found in non    # alphabetical order then remove it    if (isMax >= 0):        s = s[0 : isMax] + s[isMax + 1 : len(s)]             # s.rerase(isMax, 1);     # Otherwise remove last character    else:                 # s.erase(s.length() - 1, 1);        s = s[0: s.length() - 1]     # Print the resultant subsequence    print(s) # Driver Codeif __name__ == '__main__':         # Given String S    S = "geeksforgeeks"     # Function Call    firstSubsequence(S) # This code is contributed by Princi Singh
// C# program for the above approachusing System; class GFG{ // Function to find the lexicographically// smallest subsequence of length N-1static void firstSubsequence(String s){         // Store index of character    // to be deleted    int isMax = -1;     // Traverse the String    for(int i = 0; i < s.Length - 1; i++)    {                 // If ith character > (i + 1)th        // character then store it        if (s[i] > s[i + 1])        {            isMax = i;            break;        }    }     // If any character found in non    // alphabetical order then remove it    if (isMax >= 0)    {        s = s.Substring(0, isMax) +            s.Substring(isMax + 1);        // s.rerase(isMax, 1);    }     // Otherwise remove last character    else    {        //s.erase(s.Length - 1, 1);        s = s.Substring(0, s.Length - 1);             }     // Print the resultant subsequence    Console.Write(s);} // Driver Codepublic static void Main(String[] args){         // Given String S    String S = "geeksforgeeks";     // Function Call    firstSubsequence(S);}} // This code is contributed by Amit Katiyar
<script>// Javascript program for the above approach // Function to find the lexicographically// smallest subsequence of length N-1function firstSubsequence(s){    // Store index of character    // to be deleted    let isMax = -1;      // Traverse the String    for(let i = 0; i < s.length - 1; i++)    {                  // If ith character > (i + 1)th        // character then store it        if (s[i] > s[i + 1])        {            isMax = i;            break;        }    }      // If any character found in non    // alphabetical order then remove it    if (isMax >= 0)    {        s = s.substring(0, isMax) +            s.substring(isMax + 1);        // s.rerase(isMax, 1);    }      // Otherwise remove last character    else    {        //s.erase(s.length() - 1, 1);        s = s.substring(0, s.length - 1);              }      // Print the resultant subsequence    document.write(s);} // Driver Code// Given String Slet S = "geeksforgeeks"; // Function CallfirstSubsequence(S); // This code is contributed by unknown2108</script>
Output: 
eeksforgeeks
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
amit143katiyar
ipg2016107
princi singh
patel2127
unknown2108
sunnykr2
lexicographic-ordering
subsequence
Combinatorial
Sorting
Strings
Strings
Sorting
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Combinational Sum
Count of subsets with sum equal to X
Python program to get all subsets of given size of a set
Print all possible strings of length k that can be formed from a set of n characters
Print all subsets of given size of a set