Build lexicographically smallest String from two given Strings
Last Updated :
08 Nov, 2022
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, and add it to the end of Z.
Note: You can only K consecutive operations in a single string. Perform the operations until either X or Y becomes empty.
Examples:
Input: X = "aaaa", Y ="bbbb", K = 2
Output: aabaa
Explanation: The smallest lexicographically string possible for K = 2 is "aabaa".
Select "aa" from X. Then select "b" from Y and "aa" from X again.
Input: X = "ccaaa", Y ="bbeedd", K = 3
Output: aaabbcc
Approach: To solve the problem follow the below idea:
We solve this problem by using greedy method.
Sort the strings X and Y and take the characters as follows:
- Keep selecting consecutive characters from the string whose characters are lexicographically smaller till K consecutive characters are selected, or all the characters of that string are selected or the character of the other string becomes lexicographically smaller.
- If K consecutive characters are selected, then do the above operation again on the other string. Repeat these two processes till at least one of the string becomes empty.
Follow the below steps to solve the problem:
- Sort the strings in ascending order.
- Initialize the pointers i, j, p, q to 0.
- Run the loop while any of the strings is non-empty.
- If (X[i] < Y[j] and p < k) or q == k, then,
- Append X[i] to the end of Z and increment i and p by 1 and set q = 0.
- Otherwise, do the following:
- Append Y[j] to the end of Z and increment j and q by 1 and also set p to 0.
- Return the resultant string.
Below is the implementation of the above approach.
C++
// C++ code to implement the above approach
#include <bits/stdc++.h>
using namespace std;
#define ll long long
// Function to build smallest lexicographically
// string possible for given K
string buildString(string a, string b, int k)
{
// Calculate the sizes
ll n = a.size();
ll m = b.size();
// Sort the strings
sort(a.begin(), a.end());
sort(b.begin(), b.end());
// Initialize the pointers
ll i = 0, j = 0, p = 0, q = 0;
string c = "";
// While any of string is non-empty
while (i < n && j < m) {
if ((a[i] < b[j] && p < k) || q == k) {
c += a[i];
p++;
i++;
q = 0;
}
else {
c += b[j];
q++;
j++;
p = 0;
}
}
// Return resultant string
return c;
}
// Driver Code
int main()
{
string X = "aaaa";
string Y = "bbbb";
int K = 2;
// Function call
cout << buildString(X, Y, K) << endl;
return 0;
}
Java
// JAVA code to implement the above approach
import java.util.Arrays;
import java.util.Scanner;
import java.io.*;
class GFG
{
// Function to build smallest lexicographically
// string possible for given k
static String buildstring(String a, String b, int k)
{
// Calculate the sizes
int n = a.length();
int m = b.length();
//Sort the strings
char c1[] = a.toCharArray();
Arrays.sort(c1);
a = new String(c1);
char c2[] = b.toCharArray();
Arrays.sort(c2);
b = new String(c2);
// Initialize the pointers
int i = 0, j = 0, p = 0, q = 0;
String c = "";
// While any of string is non-empty
while (i < n && j < m)
{
if ((a.charAt(i) < b.charAt(j) && p < k) || q == k)
{
c += a.charAt(i);
p++;
i++;
q = 0;
}
else
{
c += b.charAt(j);
q++;
j++;
p = 0;
}
}
// Return resultant string
return c;
}
// driver code
public static void main (String[] args)
{
String x = "aaaa";
String y = "bbbb";
int k = 2;
// function call
System.out.println(buildstring(x,y,k));
}
}
// This code is written by Ujjwal Kumar Bhardwaj
Python3
# Python3 code to implement the above approach
# Function to build smallest lexicographically
# string possible for given K
def buildString(a, b, k) :
# Calculate the sizes
n = len(a);
m = len(b);
a = list(a)
b = list(b)
# Sort the strings
a.sort();
b.sort();
# Initialize the pointers
i = 0; j = 0; p = 0; q = 0;
c = "";
# While any of string is non-empty
while (i < n and j < m) :
if ((a[i] < b[j] and p < k) or q == k) :
c += a[i];
p += 1;
i += 1;
q = 0;
else :
c += b[j];
q += 1;
j += 1;
p = 0;
c = "".join(c)
# Return resultant string
return c;
# Driver Code
if __name__ == "__main__" :
X = "aaaa";
Y = "bbbb";
K = 2;
# Function call
print(buildString(X, Y, K));
# This code is contributed by AnkThon
C#
// C# code to implement the above approach
using System;
using System.Collections;
public class GFG {
// Function to build smallest lexicographically
// string possible for given k
static String buildstring(String a, String b, int k)
{
// Calculate the sizes
int n = a.Length;
int m = b.Length;
// Sort the strings
char[] c1 = a.ToCharArray();
Array.Sort(c1);
a = new String(c1);
char[] c2 = b.ToCharArray();
Array.Sort(c2);
b = new String(c2);
// Initialize the pointers
int i = 0, j = 0, p = 0, q = 0;
String c = "";
// While any of string is non-empty
while (i < n && j < m) {
if ((a[i] < b[j] && p < k) || q == k) {
c += a[i];
p++;
i++;
q = 0;
}
else {
c += b[j];
q++;
j++;
p = 0;
}
}
// Return resultant string
return c;
}
static public void Main()
{
// Code
String x = "aaaa";
String y = "bbbb";
int k = 2;
// function call
Console.WriteLine(buildstring(x, y, k));
}
}
// This code is written by lokeshmvs21.
JavaScript
<script>
// Javascript code to implement the above approach
// Function to build smallest lexicographically
// string possible for given K
function buildString( a, b, k)
{
// Calculate the sizes
let n = a.length;
let m = b.length;
// Sort the strings
a.sort;
b.sort;
// Initialize the pointers
let i = 0, j = 0, p = 0, q = 0;
let c = "";
// While any of string is non-empty
while (i < n && j < m) {
if ((a[i] < b[j] && p < k) || q == k) {
c += a[i];
p++;
i++;
q = 0;
}
else {
c += b[j];
q++;
j++;
p = 0;
}
}
// Return resultant string
return c;
}
// Driver Code
let X = "aaaa";
let Y = "bbbb";
let K = 2;
// Function call
document.write(buildString(X, Y, K));
// This code is contributed by hrithikgarg03188.
</script>
Time Complexity: O(N*logN +M*logM)
Auxiliary Space: O(N+M)
Similar Reads
Lexicographically smallest string whose hamming distance from given string is exactly K Given a lowercase string A of length N and an integer K, find the lexicographically smallest string B of the same length as A such that hamming distance between A and B is exactly K. Examples: Input : A = "pqrs", k = 1. Output : aqrs We can differ by at most one character. So we put 'a' in the begin
8 min read
Lexicographically smallest string which is not a subsequence of given string Given a string S, the task is to find the string which is lexicographically smallest and not a subsequence of the given string S. Examples: Input: S = "abcdefghijklmnopqrstuvwxyz"Output: aaExplanation:String "aa" is the lexicographically smallest string which is not present in the given string as a
5 min read
Lexicographically smallest String by pair swapping Suppose you are given a string Str of length N and a set of Pairs ( i, j such that 0 <= i < j < N, 0 based indexing). Pair âi, jâ means that you can swap the ith and jth characters in the string any number of times. You have to output the lexicographically smallest string that can be produc
11 min read
Lexicographically smallest string possible by merging two sorted strings Given two sorted strings S1 and S2 of lengths N and M respectively, the task is to construct lexicographically the smallest string possible by merging the two given strings and not changing the order of occurrence of characters. Examples: Input: S1 = "eefgkors", S2 = "eegks"Output: "eeeefggkkorss"Ex
7 min read
Find the winner of the game to build the lexicographically smaller string Two players are playing a game where string str is given. The first player can take the characters at even indices and the second player can take the characters at odd indices. The player which can build the lexicographically smaller string than the other player wins the game. Print the winner of th
6 min read
Lexicographically Kth-smallest string having 'a' X times and 'b' Y times Given three non-negative integers, X, Y, and K, the task is to find the Kth smallest lexicographical string having X occurrences of character 'a' and Y occurrences of character 'b'. Examples: Input: X = 2, Y = 3, K = 3Output: abbabExplanation: First lexicographical smallest string = "aabbb".Second l
15+ min read