Lexicographically smallest string formed by removing at most one character
Given a string str, the task is to find the lexicographically smallest string that can be formed by removing at most one character from the given string.
Examples:
Input: str = "abcda"
Output: abca
One can remove 'd' to get "abca" which is
the lexicographically smallest string possible.
Input: str = "aaa'
Output: aa
Approach: Traverse the string and delete the i-th character at the first point where s[i]>s[i+1]. If in case there is no such character then delete the last character in the string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string smallest(string s)
{
int l = s.length();
bool flag= false ;
string ans = "" ;
int index=-1;
for ( int i = 0; i < l-1; i++) {
if (s[i] > s[i + 1]) {
flag= true ;
index=i;
break ;
}
}
if (flag== false )
{
ans=s;
return ans;
}
for ( int j = 0; j < l; j++) {
if (index != j)
ans += s[j];
}
return ans;
}
int main()
{
string s = "abcda" ;
cout << smallest(s);
return 0;
}
|
Java
class GFG {
static String smallest(String s) {
int l = s.length();
String ans = "" ;
for ( int i = 0 ; i < l- 1 ; i++) {
if (s.charAt(i) > s.charAt(i + 1 )) {
for ( int j = 0 ; j < l; j++) {
if (i != j) {
ans += s.charAt(j);
}
}
return ans;
}
}
ans = s.substring( 0 , l - 1 );
return ans;
}
public static void main(String[] args) {
String s = "abcda" ;
System.out.println(smallest(s));
}
}
|
Python3
def smallest(s):
l = len (s)
ans = ""
for i in range (l - 1 ):
if (s[i] > s[i + 1 ]):
for j in range (l):
if (i ! = j):
ans + = s[j]
return ans
ans = s[ 0 : l - 1 ]
return ans
if __name__ = = "__main__" :
s = "abcda"
print (smallest(s))
|
C#
using System;
class GFG
{
static String smallest(String s)
{
int l = s.Length;
String ans = "" ;
for ( int i = 0; i < l-1; i++)
{
if (s[i] > s[i + 1])
{
for ( int j = 0; j < l; j++)
{
if (i != j)
{
ans += s[j];
}
}
return ans;
}
}
ans = s.Substring(0, l - 1);
return ans;
}
public static void Main()
{
String s = "abcda" ;
Console.Write(smallest(s));
}
}
|
Javascript
<script>
function smallest(s)
{
let l = s.length;
let ans = "" ;
for (let i = 0; i < l-1; i++)
{
if (s[i] > s[i+1]) {
for (let j = 0; j < l; j++) {
if (i != j) {
ans += s[j];
}
}
return ans;
}
}
ans = s.substring(0, l - 1);
return ans;
}
let s = "abcda" ;
document.write(smallest(s));
</script>
|
Complexity Analysis:
- Time complexity: O(n) where n is the length of the string
- Auxiliary Space: O(n) since we are storing the answer in form of string.
Last Updated :
08 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...