# Generate a String from given Strings P and Q based on the given conditions

• Difficulty Level : Medium
• Last Updated : 09 Jun, 2021

Given two strings P and Q, the task is to generate a string S satisfying the following conditions:

• Find S such that P is rearranged and Q is a substring in it.
• All the characters before Q in S should be smaller than or equal to the first character in Q and in lexicographic order.
• The rest of the characters should be present after Q in lexicographic order

Note: All characters of Q are always present in P and length of Q is always less than or equal to the length of P.

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.

Examples:

Input : P = “geeksforgeeksfor” Q = “for”
Explanation:
The characters ‘e’ and ‘f’ are the only characters here which are less than or equal to ‘f’ (first character of Q).
So, before “for” the string is lexicographically equal to eeeef.
The rest of the characters in P are greater than ‘f’, so they are placed after “for” in lexicographic order.
Thus, after “for”, the string is ggkkorss.

Input : P = “lexicographical” Q = “gap”
Output : accegaphiillorx
Explanation:
The string accegaphiillorx satisfies the above conditions for string P and Q.

Approach: The idea is to find the frequencies of all the characters in P and Q to solve the problem.

• Maintain an array of frequencies of all the alphabets in P and Q.
• After finding the frequencies, segregate the characters in P according to the first character in Q and add them to the resulting string.
• Return the resulting string at the end.

Below is the implementation of the above approach:

## C++

 `// C++ program to implement``// the above approach``#include ``using` `namespace` `std;` `// Function to generate a string S from string P``// and Q according to the given conditions``void` `manipulateStrings(string P, string Q)``{` `    ``// Stores the frequencies``    ``int` `freq;``    ``memset``(freq, 0, ``sizeof``(freq));``    ` `    ``// Counts occurrences of each characters``    ``for``(``int` `i = 0; i < P.size(); i++)``    ``{``        ``freq[P[i] - ``'a'``]++;``    ``}` `    ``// Reduce the count of the character``    ``// which is also present in Q``    ``for``(``int` `i = 0; i < Q.size(); i++)``    ``{``        ``freq[Q[i] - ``'a'``]--;``    ``}` `    ``// Stores the resultant string``    ``string sb = ``""``;` `    ``// Index in freq[] to segregate the string``    ``int` `pos = Q - ``'a'``;` `    ``for``(``int` `i = 0; i <= pos; i++)``    ``{``        ``while` `(freq[i] > 0)``        ``{``            ``char` `c = (``char``)(``'a'` `+ i);``            ``sb += c;``            ``freq[i]--;``        ``}``    ``}` `    ``// Add Q to the resulting string``    ``sb += Q;` `    ``for``(``int` `i = pos + 1; i < 26; i++)``    ``{``        ``while` `(freq[i] > 0)``        ``{``            ``char` `c = (``char``)(``'a'` `+ i);``            ``sb += c;``            ``freq[i]--;``        ``}``    ``}` `    ``cout << sb << endl;``}` `// Driver Code``int` `main()``{``    ``string P = ``"geeksforgeeksfor"``;``    ``string Q = ``"for"``;``    ` `    ``// Function call``    ``manipulateStrings(P, Q);``}` `// This code is contributed by Amit Katiyar`

## Java

 `// Java Program to implement``// the above approach``import` `java.util.*;``import` `java.lang.*;``import` `java.io.*;` `class` `GFG {` `    ``// Function to generate a string S from string P``    ``// and Q according to the given conditions``    ``public` `static` `void` `manipulateStrings(String P,``                                         ``String Q)``    ``{` `        ``// Stores the frequencies``        ``int``[] freq = ``new` `int``[``26``];` `        ``// Counts occurrences of each characters``        ``for` `(``int` `i = ``0``; i < P.length(); i++) {``            ``freq[P.charAt(i) - ``'a'``]++;``        ``}` `        ``// Reduce the count of the character``        ``// which is also present in Q``        ``for` `(``int` `i = ``0``; i < Q.length(); i++) {``            ``freq[Q.charAt(i) - ``'a'``]--;``        ``}` `        ``// Stores the resultant string``        ``StringBuilder sb``            ``= ``new` `StringBuilder();` `        ``// Index in freq[] to segregate the string``        ``int` `pos = Q.charAt(``0``) - ``'a'``;` `        ``for` `(``int` `i = ``0``; i <= pos; i++) {``            ``while` `(freq[i] > ``0``) {``                ``char` `c = (``char``)(``'a'` `+ i);``                ``sb.append(c);``                ``freq[i]--;``            ``}``        ``}` `        ``// Add Q to the resulting string``        ``sb.append(Q);` `        ``for` `(``int` `i = pos + ``1``; i < ``26``; i++) {``            ``while` `(freq[i] > ``0``) {``                ``char` `c = (``char``)(``'a'` `+ i);``                ``sb.append(c);``                ``freq[i]--;``            ``}``        ``}` `        ``System.out.println(sb);``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``String P = ``"geeksforgeeksfor"``;``        ``String Q = ``"for"``;``        ``// Function call``        ``manipulateStrings(P, Q);``    ``}``}`

## Python3

 `# Python3 program to implement``# the above approach` `# Function to generate a string S``# from string P and Q according to``# the given conditions``def` `manipulateStrings(P, Q):`` ` `    ``# Stores the frequencies``    ``freq ``=` `[``0` `for` `i ``in` `range``(``26``)];``     ` `    ``# Counts occurrences of each characters``    ``for` `i ``in` `range``(``len``(P)):``        ``freq[``ord``(P[i]) ``-` `ord``(``'a'``)] ``+``=` `1`` ` `    ``# Reduce the count of the character``    ``# which is also present in Q``    ``for` `i ``in` `range``(``len``(Q)):``        ``freq[``ord``(Q[i]) ``-` `ord``(``'a'``)] ``-``=` `1`` ` `    ``# Stores the resultant string``    ``sb ``=` `""`` ` `    ``# Index in freq[] to segregate the string``    ``pos ``=` `ord``(Q[``0``]) ``-` `ord``(``'a'``)``    ` `    ``for` `i ``in` `range``(pos ``+` `1``):``        ``while` `freq[i] > ``0``:``            ``sb ``+``=` `chr``(``ord``(``'a'``) ``+` `i)``            ``freq[i] ``-``=` `1`` ` `    ``# Add Q to the resulting string``    ``sb ``+``=` `Q``    ` `    ``for` `i ``in` `range``(pos ``+` `1``, ``26``):``        ``while` `freq[i] > ``0``:``            ``sb ``+``=` `chr``(``ord``(``'a'``) ``+` `i)``            ``freq[i] ``-``=` `1``    ` `    ``print``(sb)``    ` `# Driver Code``if` `__name__``=``=``"__main__"``:``    ` `    ``P ``=` `"geeksforgeeksfor"``;``    ``Q ``=` `"for"``;``     ` `    ``# Function call``    ``manipulateStrings(P, Q);` `# This code is contributed by rutvik_56`

## C#

 `// C# Program to implement``// the above approach``using` `System;``class` `GFG{` `  ``// Function to generate a string S from string P``  ``// and Q according to the given conditions``  ``public` `static` `void` `manipulateStrings(String P,``                                       ``String Q)``  ``{` `    ``// Stores the frequencies``    ``int``[] freq = ``new` `int``;` `    ``// Counts occurrences of each characters``    ``for` `(``int` `i = 0; i < P.Length; i++)``    ``{``      ``freq[P[i] - ``'a'``]++;``    ``}` `    ``// Reduce the count of the character``    ``// which is also present in Q``    ``for` `(``int` `i = 0; i < Q.Length; i++)``    ``{``      ``freq[Q[i] - ``'a'``]--;``    ``}` `    ``// Stores the resultant string``    ``String sb = ``""``;` `    ``// Index in []freq to segregate the string``    ``int` `pos = Q - ``'a'``;` `    ``for` `(``int` `i = 0; i <= pos; i++)``    ``{``      ``while` `(freq[i] > 0)``      ``{``        ``char` `c = (``char``)(``'a'` `+ i);``        ``sb += c;``        ``freq[i]--;``      ``}``    ``}` `    ``// Add Q to the resulting string``    ``sb += Q;` `    ``for` `(``int` `i = pos + 1; i < 26; i++)``    ``{``      ``while` `(freq[i] > 0)``      ``{``        ``char` `c = (``char``)(``'a'` `+ i);``        ``sb += c;``        ``freq[i]--;``      ``}``    ``}``    ``Console.WriteLine(sb);``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main(String[] args)``  ``{``    ``String P = ``"geeksforgeeksfor"``;``    ``String Q = ``"for"``;``    ` `    ``// Function call``    ``manipulateStrings(P, Q);``  ``}``}` `// This code is contributed by Rohit_ranjan`

## Javascript

 ``
Output:
`eeeefforggkkorss`

Time Complexity: O(N+M) where N and M are the respective lengths of P and Q.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up