# Lexicographically smallest string possible by inserting given character

• Difficulty Level : Medium
• 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:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

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

 `// C++ Program to implement the``// above approach``#include ``using` `namespace` `std;` `// Function to obtain lexicographically``// smallest string possible by inserting``// character c in the string s``string SmallestString(string s, ``char` `c)``{` `    ``// Traverse the string``    ``for` `(``int` `i = 0; i < s.size(); i++) {` `        ``// If the current character is greater``        ``// than the given character``        ``if` `(s[i] > c) {` `            ``// Insert the character before``            ``// the greater character``            ``s.insert(i, 1, c);` `            ``// Return the string``            ``return` `s;``        ``}``    ``}` `    ``// Append the character at the end``    ``s += c;` `    ``// Return the string``    ``return` `s;``}` `// Driver Code``int` `main()``{``    ``string S = ``"acd"``;``    ``char` `C = ``'b'``;` `    ``cout << SmallestString(S, C) << endl;` `    ``return` `0;``}`

## Java

 `// Java program to implement the``// above approach``import` `java.util.*;` `class` `GFG{` `// Function to obtain lexicographically``// smallest String possible by inserting``// character c in the String s``static` `String SmallestString(String s, ``char` `c)``{``    ` `    ``// Traverse the String``    ``for``(``int` `i = ``0``; i < s.length(); i++)``    ``{``        ` `        ``// If the current character is greater``        ``// than the given character``        ``if` `(s.charAt(i) > c)``        ``{``            ` `            ``// Insert the character before``            ``// the greater character``            ``String temp = s;``            ``s = s.substring(``0``, i);``            ``s += c;``            ``s += temp.substring(i, temp.length());``            ` `            ``// Return the String``            ``return` `s;``        ``}``    ``}``    ` `    ``// Append the character at the end``    ``s += c;``    ` `    ``// Return the String``    ``return` `s;``}` `// Driver Code``public` `static` `void` `main(String args[])``{``    ``String S = ``"acd"``;``    ``char` `C = ``'b'``;``    ` `    ``System.out.println(SmallestString(S, C));``}``}` `// This code is contributed by ipg2016107`

## Python3

 `# Python3 Program to implement``# the above approach` `# Function to obtain lexicographically``# smallest string possible by inserting``# character c in the string s``def` `SmallestString(s, c):` `    ``i ``=` `0` `    ``# Traverse the string``    ``while``(i < ``len``(s)):` `      ``# Check if current character is``      ``# greater than the given character``        ``if` `s[i] > c:` `            ``# Insert the character before``            ``# the first greater character``            ``s ``=` `s[:i] ``+` `c ``+` `s[i:]` `            ``# Return the string``            ``return` `s``        ``i ``=` `i ``+` `1` `    ``# Append the character at the end``    ``s ``=` `s ``+` `c` `    ``# Return the string``    ``return` `s`  `S ``=` `'abd'``C ``=` `'c'` `# Function call``print``(SmallestString(S, C))`

## C#

 `// C# program to implement the``// above approach``using` `System;` `class` `GFG{``    ` `// Function to obtain lexicographically``// smallest String possible by inserting``// character c in the String s``static` `String SmallestString(String s, ``char` `c)``{``    ` `    ``// Traverse the String``    ``for``(``int` `i = 0; i < s.Length; i++)``    ``{``        ` `        ``// If the current character is greater``        ``// than the given character``        ``if` `(s[i] > c)``        ``{``            ` `            ``// Insert the character before``            ``// the greater character``            ``String temp = s;``            ``s = s.Substring(0, i);``            ``s += c;``            ``s += temp.Substring(i, temp.Length - 1);``            ` `            ``// Return the String``            ``return` `s;``        ``}``    ``}``    ` `    ``// Append the character at the end``    ``s += c;``    ` `    ``// Return the String``    ``return` `s;``}` `// Driver Code``public` `static` `void` `Main(String []args)``{``    ``String S = ``"acd"``;``    ``char` `C = ``'b'``;``    ` `    ``Console.WriteLine(SmallestString(S, C));``}``}` `// This code is contributed by aashish1995`

## Javascript

 ``
Output:
`abcd`

Time Complexity: O(len(str))
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up