Given a string S of length N, consisting of lowercase alphabets, the task is to find the lexicographically longest string that can be obtained by replacing at most K characters from the given string.
Examples:
Input: S = “dbza”, K = 1
Output: zbza
Explanation: Replace S[0] (= ‘d’) with ‘z’ to obtain the lexicographically largest string.
Input: S = “zzzz”, K = 2
Output: zzzz
Approach: The given problem can be solved by using the Greedy Approach. The idea is to traverse the array from left to right and replace all the non z characters with z. Follow the steps below to solve the problem:
- Run a loop for i = 0 to the length of the string:
- If the current character is not equal to z, and K is not equal to 0:
- Then, replace the current character with z.
- K = K – 1.
- Finally, return the modified string.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
string largestString(string s, int k)
{
for ( int i = 0; i < s.size(); i++) {
if (s[i] != 'z' && k > 0) {
s[i] = 'z' ;
k--;
}
}
return s;
}
int main()
{
string s = "dbza" ;
int k = 1;
cout << largestString(s, k) << endl;
return 0;
}
|
Java
class GFG{
static String largestString(String s, int k)
{
for ( int i = 0 ; i < s.length(); i++)
{
if (s.charAt(i) != 'z' && k > 0 )
{
s = s.replace(s.charAt(i), 'z' );
k--;
}
}
return s;
}
public static void main(String args[])
{
String s = "dbza" ;
int k = 1 ;
System.out.println(largestString(s, k));
}
}
|
Python3
def largestString(s, k):
for i in range ( len (s)):
if (s[i] ! = 'z' and k > 0 ):
s[i] = 'z'
k - = 1
return "".join(s)
if __name__ = = '__main__' :
s = "dbza"
k = 1
print (largestString([i for i in s], k))
|
C#
using System;
using System.Collections.Generic;
class GFG{
static string largestString( string s, int k)
{
for ( int i = 0; i < s.Length; i++)
{
if (s[i] != 'z' && k > 0)
{
s = s.Replace(s[i], 'z' );
k--;
}
}
return s;
}
public static void Main()
{
string s = "dbza" ;
int k = 1;
Console.Write(largestString(s, k));
}
}
|
Javascript
<script>
function largestString(s, k)
{
for (let i = 0; i < s.length; i++) {
if (s[i] != 'z' && k > 0) {
s = s.substring(0, i) + 'z' + s.substring(i + 1);
k--;
}
}
return s;
}
var s = "dbza" ;
var k = 1;
document.write(largestString(s, k));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)