Lexicographically smallest string possible by inserting given character
Last Updated :
21 Apr, 2021
Given a string S and a character C, the task is to place a character in the string in such a way that the string obtained is the lexicographically smallest string.
Examples:
Input: S = “acd”, C = ‘b’
Output: “abcd”
Explanation: The possible strings formed by placing the character C in string at different indices are [“bacd”, “abcd”, “acbd”, “acdb”]
The lexicographically smallest string obtained is “abcd”.
Input: S = “abcd”, C=’e’
Output: “abcde”
Explanation: The possible strings formed by placing the character C in string at different indices are {“eabcd”, “aebcd”, “abecd”, “abced”, “abcde”}.
The lexicographically smallest string is “abcde”.
Approach: The idea is to place the character just before the first character which is lexicographically greater than the character C in the string. If no character in the string is found to be greater than C, insert the character at the end.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string SmallestString(string s, char c)
{
for ( int i = 0; i < s.size(); i++) {
if (s[i] > c) {
s.insert(i, 1, c);
return s;
}
}
s += c;
return s;
}
int main()
{
string S = "acd" ;
char C = 'b' ;
cout << SmallestString(S, C) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static String SmallestString(String s, char c)
{
for ( int i = 0 ; i < s.length(); i++)
{
if (s.charAt(i) > c)
{
String temp = s;
s = s.substring( 0 , i);
s += c;
s += temp.substring(i, temp.length());
return s;
}
}
s += c;
return s;
}
public static void main(String args[])
{
String S = "acd" ;
char C = 'b' ;
System.out.println(SmallestString(S, C));
}
}
|
Python3
def SmallestString(s, c):
i = 0
while (i < len (s)):
if s[i] > c:
s = s[:i] + c + s[i:]
return s
i = i + 1
s = s + c
return s
S = 'abd'
C = 'c'
print (SmallestString(S, C))
|
C#
using System;
class GFG{
static String SmallestString(String s, char c)
{
for ( int i = 0; i < s.Length; i++)
{
if (s[i] > c)
{
String temp = s;
s = s.Substring(0, i);
s += c;
s += temp.Substring(i, temp.Length - 1);
return s;
}
}
s += c;
return s;
}
public static void Main(String []args)
{
String S = "acd" ;
char C = 'b' ;
Console.WriteLine(SmallestString(S, C));
}
}
|
Javascript
<script>
function SmallestString(s, c)
{
for (let i = 0; i < s.length; i++)
{
if (s[i] > c)
{
let temp = s;
s = s.substring(0, i);
s += c;
s += temp.substring(i, temp.length);
return s;
}
}
s += c;
return s;
}
let S = "acd" ;
let C = 'b' ;
document.write(SmallestString(S, C));
</script>
|
Time Complexity: O(len(str))
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...