Open In App

Lexicographically smallest subsequence possible by removing a character from given string

Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the lexicographically
// smallest subsequence of length N-1
void 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 Code
int main()
{
    // Given string S
    string S = "geeksforgeeks";
 
    // Function Call
    firstSubsequence(S);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the lexicographically
// smallest subsequence of length N-1
static 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 Code
public static void main(String[] args)
{
     
    // Given String S
    String S = "geeksforgeeks";
 
    // Function Call
    firstSubsequence(S);
}
}
 
// This code is contributed by Amit Katiyar


Python3




# Python3 program for the above approach
 
# Function to find the lexicographically
# smallest subsequence of length N-1
def 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 Code
if __name__ == '__main__':
     
    # Given string S
    S = "geeksforgeeks"
 
    # Function Call
    firstSubsequence(S)
 
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the lexicographically
// smallest subsequence of length N-1
static 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 Code
public static void Main()
{
     
    // Given string S
    string S = "geeksforgeeks";
 
    // Function Call
    firstSubsequence(S);
}
}
 
// This code is contributed by ipg2016107


Javascript




<script>
// Javascript program for the above approach
 
// Function to find the lexicographically
// smallest subsequence of length N-1
function 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 S
let S = "geeksforgeeks";
 
// Function Call
firstSubsequence(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++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the lexicographically
// smallest subsequence of length N-1
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.erase(isMax, 1);
    }
 
    // Otherwise remove last character
    else {
        s.erase(s.length() - 1, 1);
    }
 
    // Print the resultant subsequence
    cout << s;
}
 
// Driver Code
int main()
{
    // Given string S
    string S = "geeksforgeeks";
 
    // Function Call
    firstSubsequence(S);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the lexicographically
// smallest subsequence of length N-1
static 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 Code
public static void main(String[] args)
{
     
    // Given String S
    String S = "geeksforgeeks";
 
    // Function Call
    firstSubsequence(S);
}
}
 
// This code is contributed by Princi Singh


Python3




# Python3 program for the above approach
 
# Function to find the lexicographically
# smallest subsequence of length N-1
def 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 Code
if __name__ == '__main__':
     
    # Given String S
    S = "geeksforgeeks"
 
    # Function Call
    firstSubsequence(S)
 
# This code is contributed by Princi Singh


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to find the lexicographically
// smallest subsequence of length N-1
static 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 Code
public static void Main(String[] args)
{
     
    // Given String S
    String S = "geeksforgeeks";
 
    // Function Call
    firstSubsequence(S);
}
}
 
// This code is contributed by Amit Katiyar


Javascript




<script>
// Javascript program for the above approach
 
// Function to find the lexicographically
// smallest subsequence of length N-1
function 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 S
let S = "geeksforgeeks";
 
// Function Call
firstSubsequence(S);
 
// This code is contributed by unknown2108
</script>


Output: 

eeksforgeeks

Time Complexity: O(N)
Auxiliary Space: O(1)



Last Updated : 19 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads