Given a string str consisting of lowercase alphabets and an integer K, you can perform the following operations on str
- Initialize an empty string X = “”.
- Take any character from the first K characters of str and append it to X.
- Remove the chosen character from str.
- Repeat the above steps while there are characters left in str.
The task is to generate X such that it is lexicographically the smallest possible then print the generated string. Examples:
Input: str = “geek”, K = 2
Output: eegk Operation 1: str = “gek”, X = “e” Operation 2: str = “gk”, X = “ee” Operation 3: str = “k”, X = “eeg” Operation 4: str = “”, X = “eegk”
Input: str = “geeksforgeeks”, K = 5
Output: eefggeekkorss
Approach: In order to get the lexicographically smallest string, we need to take the minimum character from the first K characters every time we choose a character from str. To do that, we can put the first K characters in a priority_queue (min-heap) and then choose the smallest character and append it to X. Then, push the next character in str to the priority queue and repeat the process until there are characters left to process. Below is the implementation of the above approach:
// C++ implementation of the approach #include <bits/stdc++.h> using namespace std;
// Function to return the lexicographically // smallest required string string getSmallestStr(string S, int K)
{ // Initially empty string
string X = "" ;
// min heap of characters
priority_queue< char , vector< char >, greater< char > > pq;
// Length of the string
int i, n = S.length();
// K cannot be greater than
// the size of the string
K = min(K, n);
// First push the first K characters
// into the priority_queue
for (i = 0; i < K; i++)
pq.push(S[i]);
// While there are characters to append
while (!pq.empty()) {
// Append the top of priority_queue to X
X += pq.top();
// Remove the top element
pq.pop();
// Push only if i is less than
// the size of string
if (i < S.length())
pq.push(S[i]);
i++;
}
// Return the generated string
return X;
} // Driver code int main()
{ string S = "geeksforgeeks" ;
int K = 5;
cout << getSmallestStr(S, K);
return 0;
} |
// Java implementation of the approach import java.util.PriorityQueue;
class GFG
{ // Function to return the lexicographically
// smallest required string
static String getSmallestStr(String S, int K)
{
// Initially empty string
String X = "" ;
// min heap of characters
PriorityQueue<Character> pq = new PriorityQueue<>();
// Length of the string
int i, n = S.length();
// K cannot be greater than
// the size of the string
K = Math.min(K, n);
// First push the first K characters
// into the priority_queue
for (i = 0 ; i < K; i++)
pq.add(S.charAt(i));
// While there are characters to append
while (!pq.isEmpty())
{
// Append the top of priority_queue to X
X += pq.peek();
// Remove the top element
pq.remove();
// Push only if i is less than
// the size of string
if (i < S.length())
pq.add(S.charAt(i));
i++;
}
// Return the generated string
return X;
}
// Driver Code
public static void main(String[] args)
{
String S = "geeksforgeeks" ;
int K = 5 ;
System.out.println(getSmallestStr(S, K));
}
} // This code is contributed by // sanjeev2552 |
using System;
using System.Collections.Generic;
namespace GetSmallestString
{ class Program
{
static string GetSmallestStr( string S, int K)
{
// Initially empty string
string X = "" ;
// min heap of characters
var pq = new SortedSet< char >();
// Length of the string
int i, n = S.Length;
// K cannot be greater than
// the size of the string
K = Math.Min(K, n);
// First push the first K characters
// into the priority_queue
for (i = 0; i < K; i++)
pq.Add(S[i]);
// While there are characters to append
while (pq.Count > 0)
{
// Append the top of priority_queue to X
X += pq.Min;
// Remove the top element
pq.Remove(pq.Min);
// Push only if i is less than
// the size of string
if (i < S.Length)
pq.Add(S[i]);
i++;
}
// Return the generated string
return X;
}
static void Main( string [] args)
{
string S = "geeksforgeeks" ;
int K = 5;
Console.WriteLine(GetSmallestStr(S, K));
}
}
} // this code is contributed by writer |
// JavaScript implementation of the approach class GFG { // Function to return the lexicographically
// smallest required string
static getSmallestStr(S, K) {
// Initially empty string
let X = "" ;
// min heap of characters
let pq = [];
// Length of the string
let i, n = S.length;
// K cannot be greater than
// the size of the string
K = Math.min(K, n);
// First push the first K characters
// into the priority_queue
for (i = 0; i < K; i++) {
pq.push(S.charAt(i));
}
// Sort the priority queue in ascending order
pq.sort();
// While there are characters to append
while (pq.length > 0) {
// Append the top of priority_queue to X
X += pq[0];
// Remove the top element
pq.shift();
// Push only if i is less than
// the size of string
if (i < S.length) {
pq.push(S.charAt(i));
}
i++;
// Sort the priority queue in ascending order
pq.sort();
}
// Return the generated string
return X;
}
// Driver Code
static main() {
let S = "geeksforgeeks" ;
let K = 5;
console.log(GFG.getSmallestStr(S, K));
}
} GFG.main(); |
import heapq
def get_smallest_str(s: str , k: int ) - > str :
# Initialize an empty string
x = ""
# Create a heap of characters
pq = []
# Get the length of the string
n = len (s)
# k cannot be greater than the size of the string
k = min (k, n)
# First push the first k characters into the priority_queue
for i in range (k):
heapq.heappush(pq, s[i])
# While there are characters to append
i = k
while pq:
# Append the top of priority_queue to x
x + = heapq.heappop(pq)
# Push only if i is less than the size of string
if i < n:
heapq.heappush(pq, s[i])
i + = 1
# Return the generated string
return x
# Driver code s = "geeksforgeeks"
k = 5
print (get_smallest_str(s, k))
|
eefggeekkorss
Time Complexity: O(nlogn) where n is the length of the string.
Auxiliary Space: O(K), as extra space of size K is used to build priorityQueue