# Lexicographically smallest string possible by performing K operations on a given string

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

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 = “geek”, K = 5
Output: aaaa
Explanation:
In 1st operation: take i = 1 and j = 4, swap S and S and then change S to ‘a’. Modified string = “aeeg”.
In 2nd operation: take i = 2 and j=4, swap S and S and then change S to ‘a’. Modified string = “aaee”.
In 3rd operation: take i = 3 and j = 4, swap S and S and then change S to ‘a’. Modified string = “aaae”.
In 4th operation: take i = 3 and j = 4, swap S and S and then change S 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 ``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

 ``

Output:
`aaaaaaeegeeks`

Time complexity: O(N2)
Auxiliary space: O(1)

My Personal Notes arrow_drop_up