Lexicographically smallest string possible by performing K operations on a given string
Last Updated :
22 Apr, 2021
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 = 5
Output: aaaa
Explanation:
In 1st operation: take i = 1 and j = 4, swap S[1] and S[4] and then change S[1] to 'a'. Modified string = "aeeg".
In 2nd operation: take i = 2 and j=4, swap S[2] and S[4] and then change S[2] to 'a'. Modified string = "aaee".
In 3rd operation: take i = 3 and j = 4, swap S[3] and S[4] and then change S[3] to 'a'. Modified string = "aaae".
In 4th operation: take i = 3 and j = 4, swap S[3] and S[4] and then change S[3] to 'a'. Modified string = "aaaa".
Input: S = "geeksforgeeks", K = 6
Output: aaaaaaeegeeks
Explanation: After 6 operations, lexicographically smallest string will be "aaaaaaeegeeks".
Approach: For K?N, the lexicographically smallest possible string will be 'a' repeated N times, since, in N operations, all the characters of S can be changed to 'a'. For all other cases, the idea is to iterate the string S using variable i, find a suitable j for which S[j]>S[i], and then convert S[j] to S[i] and S[i] to 'a'. Continue this process while K>0.
Follow the steps below to solve the problem:
- If K ? N, convert every character of string S to 'a' and print the string, S.
- Otherwise:
Below is the implementation of the above approach:
C++
// C++ program to implement the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to find the lexicographically
// smallest possible string by performing
// K operations on string S
void smallestlexicographicstring(string s, int k)
{
// Store the size of string, s
int n = s.size();
// Check if k>=n, if true, convert
// every character to 'a'
if (k >= n) {
for (int i = 0; i < n; i++) {
s[i] = 'a';
}
cout << s;
return;
}
// Iterate in range[0, n - 1] using i
for (int i = 0; i < n; i++) {
// When k reaches 0, break the loop
if (k == 0) {
break;
}
// If current character is 'a',
// continue
if (s[i] == 'a')
continue;
// Otherwise, iterate in the
// range [i + 1, n - 1] using j
for (int j = i + 1; j < n; j++) {
// Check if s[j] > s[i]
if (s[j] > s[i]) {
// If true, set s[j] = s[i]
// and break out of the loop
s[j] = s[i];
break;
}
// Check if j reaches the last index
else if (j == n - 1)
s[j] = s[i];
}
// Update S[i]
s[i] = 'a';
// Decrement k by 1
k--;
}
// Print string
cout << s;
}
// Driver Code
int main()
{
// Given String, s
string s = "geeksforgeeks";
// Given k
int k = 6;
// Function Call
smallestlexicographicstring(s, k);
return 0;
}
Java
// Java program to implement the above approach
public class GFG
{
// Function to find the lexicographically
// smallest possible string by performing
// K operations on string S
static void smallestlexicographicstring(char[] s, int k)
{
// Store the size of string, s
int n = s.length;
// Check if k>=n, if true, convert
// every character to 'a'
if (k >= n)
{
for (int i = 0; i < n; i++)
{
s[i] = 'a';
}
System.out.print(s);
return;
}
// Iterate in range[0, n - 1] using i
for (int i = 0; i < n; i++)
{
// When k reaches 0, break the loop
if (k == 0)
{
break;
}
// If current character is 'a',
// continue
if (s[i] == 'a')
continue;
// Otherwise, iterate in the
// range [i + 1, n - 1] using j
for (int j = i + 1; j < n; j++)
{
// Check if s[j] > s[i]
if (s[j] > s[i])
{
// If true, set s[j] = s[i]
// and break out of the loop
s[j] = s[i];
break;
}
// Check if j reaches the last index
else if (j == n - 1)
s[j] = s[i];
}
// Update S[i]
s[i] = 'a';
// Decrement k by 1
k--;
}
// Print string
System.out.print(s);
}
// Driver code
public static void main(String[] args)
{
// Given String, s
char[] s = ("geeksforgeeks").toCharArray();
// Given k
int k = 6;
// Function Call
smallestlexicographicstring(s, k);
}
}
// This code is contributed by divyesh072019.
Python3
# Python3 program to implement the above approach
# Function to find the lexicographically
# smallest possible string by performing
# K operations on string S
def smallestlexicographicstring(s, k):
# Store the size of string, s
n = len(s)
# Check if k>=n, if true, convert
# every character to 'a'
if (k >= n):
for i in range(n):
s[i] = 'a';
print(s, end = '')
return;
# Iterate in range[0, n - 1] using i
for i in range(n):
# When k reaches 0, break the loop
if (k == 0):
break;
# If current character is 'a',
# continue
if (s[i] == 'a'):
continue;
# Otherwise, iterate in the
# range [i + 1, n - 1] using j
for j in range(i + 1, n):
# Check if s[j] > s[i]
if (s[j] > s[i]):
# If true, set s[j] = s[i]
# and break out of the loop
s[j] = s[i];
break;
# Check if j reaches the last index
elif (j == n - 1):
s[j] = s[i];
# Update S[i]
s[i] = 'a';
# Decrement k by 1
k -= 1
# Print string
print(''.join(s), end = '');
# Driver Code
if __name__=='__main__':
# Given String, s
s = list("geeksforgeeks");
# Given k
k = 6;
# Function Call
smallestlexicographicstring(s, k);
# This code is contributed by rutvik_56.
C#
// C# program to implement the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the lexicographically
// smallest possible string by performing
// K operations on string S
static void smallestlexicographicstring(char[] s, int k)
{
// Store the size of string, s
int n = s.Length;
// Check if k>=n, if true, convert
// every character to 'a'
if (k >= n)
{
for (int i = 0; i < n; i++)
{
s[i] = 'a';
}
Console.Write(s);
return;
}
// Iterate in range[0, n - 1] using i
for (int i = 0; i < n; i++)
{
// When k reaches 0, break the loop
if (k == 0)
{
break;
}
// If current character is 'a',
// continue
if (s[i] == 'a')
continue;
// Otherwise, iterate in the
// range [i + 1, n - 1] using j
for (int j = i + 1; j < n; j++)
{
// Check if s[j] > s[i]
if (s[j] > s[i])
{
// If true, set s[j] = s[i]
// and break out of the loop
s[j] = s[i];
break;
}
// Check if j reaches the last index
else if (j == n - 1)
s[j] = s[i];
}
// Update S[i]
s[i] = 'a';
// Decrement k by 1
k--;
}
// Print string
Console.Write(s);
}
// Driver code
static void Main()
{
// Given String, s
char[] s = ("geeksforgeeks").ToCharArray();
// Given k
int k = 6;
// Function Call
smallestlexicographicstring(s, k);
}
}
// This code is contributed by divyeshrabadiya07.
JavaScript
<script>
// Javascript program to implement
// the above approach
// Function to find the lexicographically
// smallest possible string by performing
// K operations on string S
function smallestlexicographicstring(s, k)
{
// Store the size of string, s
let n = s.length;
// Check if k>=n, if true, convert
// every character to 'a'
if (k >= n)
{
for (let i = 0; i < n; i++)
{
s[i] = 'a';
}
document.write(s);
return;
}
// Iterate in range[0, n - 1] using i
for (let i = 0; i < n; i++)
{
// When k reaches 0, break the loop
if (k == 0)
{
break;
}
// If current character is 'a',
// continue
if (s[i] == 'a')
continue;
// Otherwise, iterate in the
// range [i + 1, n - 1] using j
for (let j = i + 1; j < n; j++)
{
// Check if s[j] > s[i]
if (s[j].charCodeAt() >
s[i].charCodeAt())
{
// If true, set s[j] = s[i]
// and break out of the loop
s[j] = s[i];
break;
}
// Check if j reaches the last index
else if (j == n - 1)
s[j] = s[i];
}
// Update S[i]
s[i] = 'a';
// Decrement k by 1
k--;
}
// Print string
document.write(s.join(""));
}
// Given String, s
let s = ("geeksforgeeks").split('');
// Given k
let k = 6;
// Function Call
smallestlexicographicstring(s, k);
</script>
Time complexity: O(N2)
Auxiliary space: O(1)
Similar Reads
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
Find lexicographical smallest string by performing the given operations N times Given a string S of N characters, the task is to find the smallest lexicographical string after performing each of the following operations N times in any order: Remove the 1st character of S and insert it into a stack X.Remove the top of stack X and append it to the end of another string Y which is
8 min read
Lexicographically smallest string with period K possible by replacing '?'s from a given string Given a string S consisting of N lowercase characters and character '?' and a positive integer K, the task is to replace each character '?' with some lowercase alphabets such that the given string becomes a period of K. If it is not possible to do so, then print "-1". A string is said to be a period
9 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 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