Create lexicographically minimum String using given operation
Last Updated :
13 Apr, 2023
Given a string s of length N consisting of digits from 0 to 9. Find the lexicographically minimum sequence that can be obtained from given string s by performing the given operations:
- Selecting any position i in the string and delete the digit 'd' at ith position,
- Insert min(d+1, 9) on any position in the string s.
Examples:
Input: s = " 5217 "
Output: s = " 1367 "
Explanation:
Choose 0th position, d = 5 and insert 6 i.e. min(d+1, 9) between 1 and 7 in string; s = " 2167 "
Choose 0th position, d = 2 and insert 3 i.e. min(d+1, 9) between 1 and 6 in string; s = " 1367 "
Input: s = " 09412 "
Output: s = " 01259 "
Explanation:
Choose 1st position, d = 9 and insert 9 i.e. min(d+1, 9) at last of string; s = " 04129 "
Choose 1st position, d = 4 and insert 5 i.e. min(d+1, 9) between 2 and 9 in string; s = " 0 1 2 5 9 "
Approach: Implement the idea below to solve the problem:
At each position i, we check if there is any digit sj such that sj < si and j > i. As we need the lexicographically minimum string, we need to bring the jth digit ahead of ith digit. So delete the ith digit and insert min(si+1, 9) behind the jth digit. Otherwise, if no lesser digits are present ahead of ith digit, keep the digit as it is and don't perform the operation.
Follow the below steps to implement the above idea:
- Create a suffix vector to store the minimum digit in the right part of ith position in the string.
- Run a loop from N-2 to 0 and store the minimal digit found till index i from the end. [This can be done by storing suf[i] = min( suf[i+1], s[i] ) ].
- Create a result vector that will store the digits that will be present in the final lexicographically minimum string.
- Traverse for each position from i = 0 to N-1 in the string and check if there is any digit less than the current digit (d = s[i]-'0') on the right side:
- If yes then push min(d+1, 9) in result.
- Else push (d) in the result.
- Sort the vector result and print the values [Because we can easily arrange them in that way as there is no constraint on how many times we can perform the operation].
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Function to print the minimum
// string after operation
string minimumSequence(string& s)
{
int n = s.size();
vector<int> suf(n);
string sol = "";
// Storing values in suf
suf[n - 1] = s[n - 1] - '0';
for (int i = n - 2; i >= 0; i--)
suf[i] = min(suf[i + 1], s[i] - '0');
// Storing values of final sequence
// after performing given operation
vector<int> res;
for (int i = 0; i < n; i++) {
// If smaller element is present
// beyond index i
if (suf[i] < s[i] - '0')
res.push_back(min(9, s[i] - '0' + 1));
else
res.push_back(s[i] - '0');
}
// Sort the res in increasing order
sort(res.begin(), res.end());
for (int x : res)
sol += char(x + '0');
return sol;
}
// Driver code
int main()
{
string s = "09412";
// Function call
cout << minimumSequence(s);
return 0;
}
Java
// Java code to implement the approach
import java.io.*;
import java.util.*;
class GFG {
static String MinimumSequence(String s)
{
int n = s.length();
int[] suf = new int[n];
String sol = "";
// Storing values in suf
suf[n - 1] = s.charAt(n - 1) - '0';
for (int i = n - 2; i >= 0; i--)
suf[i]
= Math.min(suf[i + 1], s.charAt(i) - '0');
// Storing values of final sequence
// after performing given operation
int[] res = new int[n];
for (int i = 0; i < n; i++) {
// If smaller element is present
// beyond index i
if (suf[i] < s.charAt(i) - '0')
res[i] = Math.min(9, s.charAt(i) - '0' + 1);
else
res[i] = s.charAt(i) - '0';
}
// Sort the res in increasing order
Arrays.sort(res);
for (int i = 0; i < res.length; i++) {
sol += res[i];
}
return sol;
}
public static void main(String[] args)
{
String s = "09412";
// Function call
System.out.println(MinimumSequence(s));
}
}
// This code is contributed by lokesh.
Python3
# python3 code to implement the approach
# Function to print the minimum
# string after operation
def minimumSequence(s):
n = len(s)
suf = [0 for _ in range(n)]
sol = ""
# Storing values in suf
suf[n - 1] = ord(s[n - 1]) - ord('0')
for i in range(n-2, -1, -1):
suf[i] = min(suf[i + 1], ord(s[i]) - ord('0'))
# Storing values of final sequence
# after performing given operation
res = []
for i in range(0, n):
# If smaller element is present
# beyond index i
if (suf[i] < ord(s[i]) - ord('0')):
res.append(min(9, ord(s[i]) - ord('0') + 1))
else:
res.append(ord(s[i]) - ord('0'))
# Sort the res in increasing order
res.sort()
for x in res:
sol += str(x)
return sol
# Driver code
if __name__ == "__main__":
s = "09412"
# Function call
print(minimumSequence(s))
# This code is contributed by rakeshsahni
C#
//c# code implementation
using System;
using System.Linq;
public class GFG {
static string MinimumSequence(string s)
{
int n = s.Length;
int[] suf = new int[n];
string sol = "";
// Storing values in suf
suf[n - 1] = s[n - 1] - '0';
for (int i = n - 2; i >= 0; i--)
suf[i] = Math.Min(suf[i + 1], s[i] - '0');
// Storing values of final sequence
// after performing given operation
int[] res = new int[n];
for (int i = 0; i < n; i++) {
// If smaller element is present
// beyond index i
if (suf[i] < s[i] - '0')
res[i] = Math.Min(9, s[i] - '0' + 1);
else
res[i] = s[i] - '0';
}
// Sort the res in increasing order
Array.Sort(res);
for (int i=0;i<res.Length;i++){
sol += res[i].ToString();
}
return sol;
}
static void Main(string[] args)
{
string s = "09412";
// Function call
Console.WriteLine(MinimumSequence(s));
}
}
// code by ksam24000
JavaScript
// Javascript code to implement the approach
// Function to print the minimum
// string after operation
function minimumSequence(s)
{
let n = s.length;
let suf =new Array(n);
let sol = "";
// Storing values in suf
suf[n - 1] = parseInt(s[n - 1]);
for (let i = n - 2; i >= 0; i--)
suf[i] = Math.min(suf[i + 1], parseInt(s[i]));
// Storing values of final sequence
// after performing given operation
let res= [];
for (let i = 0; i < n; i++) {
// If smaller element is present
// beyond index i
if (suf[i] < parseInt(s[i]))
res.push(Math.min(9, parseInt(s[i]) + 1));
else
res.push(parseInt(s[i]));
}
// Sort the res in increasing order
res.sort();
for (let x=0 ; x<res.length; x++)
sol+=res[x];
return sol;
}
// Driver code
let s = "09412";
// Function call
document.write(minimumSequence(s));
Time Complexity: O(N * log N)
Auxiliary Space: O(N)
Related Articles:
Similar Reads
Lexicographically minimum string rotation | Set 1 Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written Test More Examples: Input: GEEKSQUIZ Output: EEKSQUIZG Input: GFG Output: FGG Input: GEEKSFORGEEKS Output: EEKSFORGEEKSG Following is a simple sol
5 min read
Lexicographically smallest string after M operations Given a string S and integer M. The task is to perform exactly M operations to get lexicographical smallest string. In each operation, select one character optimally from the string and update it with immediate next character ( aaa -> aab ), so that string remain lexicographical smallest.Multiple
7 min read
Lexicographically smallest string possible by using given operations Given a string S consisting of digits from 0 to 9 inclusive, the task is to form the lexicographically smallest string by performing an operation any number of times. In one operation you can choose any position i and delete the digit d at s[i] and insert min(d+1, 9) on any position (at the beginnin
7 min read
Minimum size lexicographically smallest string which is not a substring of given string Given a string s, the task is to find the lexicographically smallest string of minimum characters that do not exist as a substring in S. Examples: Input: S = "aabacdefghijklmnopqrstuvwxyz"Output: adExplanation: All the single digit strings from [a-z] occur in the given string and in two character st
7 min read
Lexicographically largest string formed in minimum moves by replacing characters of given String Given a string S consisting of N lowercase English characters, the task is to print the lexicographically, the largest string obtained using only the minimum number of moves needed to modify the string S to a string containing the first min(N, 26) lower case English alphabet, by replacing any charac
10 min read
Minimum length of string having all permutation of given string. Given a string S where 1\leq length\; of\; S\leq 26 . Assume that all the characters in S are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present as a substring in the resulting
4 min read
Build lexicographically smallest String from two given Strings Given two strings X and Y of lowercase letters, of length N and M respectively, the task is to build another string Z by performing two types of operations: Choose any character from the string X, remove it from X, and add it to the end of Z.Choose any character from the string Y, remove it from Y,
6 min read
Javascript Program to Find Lexicographically minimum string rotation | Set 1 Write code to find lexicographic minimum in a circular array, e.g. for the array BCABDADAB, the lexicographic minimum is ABBCABDAD.Source: Google Written TestExamples: Input: GEEKSQUIZOutput: EEKSQUIZGInput: GFGOutput: FGGInput: GEEKSFORGEEKSOutput: EEKSFORGEEKSGThe following is a simple solution. L
2 min read
K-th lexicographically smallest unique substring of a given string Given a string S. The task is to print the K-th lexicographically the smallest one among the different substrings of s.A substring of s is a string obtained by taking out a non-empty contiguous part in s. For example, if s = ababc, a, bab and ababc are substrings of s, while ac, z, and an empty stri
5 min read
Lexicographically smallest string possible by performing K operations on a given string Given a string S of size N and a positive integer K, the task is to perform atmost K operations on string S to make it lexicographically smallest possible. In one operation, swap S[i] and S[j] and then change S[i] to any character, given 1 ? i < j ? N. Examples: Input: S = "geek", K = 5Output: aa
8 min read