Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
Next article icon

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

Last Updated : 13 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Examples:

Input : P = “geeksforgeeksfor” Q = “for”
Output : eeeefforggkkorss
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. 
Therefore the output is eeeefforggkkorss.

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 <bits/stdc++.h>
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[26];
    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[0] - '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.io.*;
import java.lang.*;
import java.util.*;
 
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[26];
 
        // 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[0] - '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




<script>
 
      // JavaScript Program to implement
      // the above approach
       
      // Function to generate a string S from string P
      // and Q according to the given conditions
      function manipulateStrings(P, Q) {
        // Stores the frequencies
        var freq = new Array(26).fill(0);
 
        // Counts occurrences of each characters
        for (var i = 0; i < P.length; i++) {
          freq[P[i].charCodeAt(0) - "a".charCodeAt(0)]++;
        }
 
        // Reduce the count of the character
        // which is also present in Q
        for (var i = 0; i < Q.length; i++) {
          freq[Q[i].charCodeAt(0) - "a".charCodeAt(0)]--;
        }
 
        // Stores the resultant string
        var sb = "";
 
        // Index in []freq to segregate the string
        var pos = Q[0].charCodeAt(0) - "a".charCodeAt(0);
 
        for (var i = 0; i <= pos; i++) {
          while (freq[i] > 0) {
            var c = String.fromCharCode("a".charCodeAt(0) + i);
            sb += c;
            freq[i]--;
          }
        }
 
        // Add Q to the resulting string
        sb += Q;
 
        for (var i = pos + 1; i < 26; i++) {
          while (freq[i] > 0) {
            var c = String.fromCharCode("a".charCodeAt(0) + i);
            sb += c;
            freq[i]--;
          }
        }
        document.write(sb);
      }
 
      // Driver Code
      var P = "geeksforgeeksfor";
      var Q = "for";
 
      // Function call
      manipulateStrings(P, Q);
       
</script>
 
 
Output
eeeefforggkkorss 

Time Complexity: O(N+M) where N and M are the respective lengths of P and Q. 
Auxiliary Space: O(N), using extra space for string sb.



Next Article
Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions

K

kunalsg18elec
Improve
Article Tags :
  • DSA
  • Hash
  • Searching
  • Strings
  • frequency-counting
Practice Tags :
  • Hash
  • Searching
  • Strings

Similar Reads

  • Check whether given string can be generated after concatenating given strings
    Given three strings str, A and B. The task is to check whether str = A + B or str = B + A where + denotes concatenation. Examples: Input: str = "GeeksforGeeks", A = "Geeksfo", B = "rGeeks" Output: Yes str = A + B = "Geeksfo" + "rGeeks" = "GeeksforGeeks"Input: str = "Delhicapitals", B = "Delmi", C =
    11 min read
  • Generate a string consisting of characters 'a' and 'b' that satisfy the given conditions
    Given two integers A and B, the task is to generate and print a string str such that: str must only contain the characters 'a' and 'b'.str has length A + B and the occurrence of the character 'a' is equal to A and the occurrence of character 'b' is equal to BThe sub-strings "aaa" or "bbb" must not o
    6 min read
  • Generate the String of length N according to given conditions
    Given two integers N and M. Then your task is to output the string let's say S of length N by following given conditions: S must be formed by only the first M smaller case letters of the alphabetical series.The length of LPS (Longest palindromic Substring) in S should be the minimum possible.Example
    10 min read
  • Generate all permutations of a string that follow given constraints
    Given a string, generate all permutations of it that do not contain 'B' after 'A', i.e., the string should not contain "AB" as a substring. Examples: Input : str = "ABC" Output : ACB, BAC, BCA, CBA Out of 6 permutations of "ABC", 4 follow the given constraint and 2 ("ABC" and "CAB") do not follow. I
    11 min read
  • All possible strings of any length that can be formed from a given string
    Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples: Input: abcOutput: a b c abc ab ac bc bac bca cb ca ba cab cba acbInput: abcdOutput: a b ab ba c ac ca bc cb abc acb bac bca cab cba d ad da bd db abd adb bad bda
    10 min read
  • Find the rank of a given combination from an Array of String
    Given an array of string and a string K, the task is to find the rank of the given string if we generate all the combinations of the given array of strings. Examples: Input: string = ['ab', 'pq', 'nm'], K = 'pqnm'Output: 7Explanation: All combination generated are :-'' -------------------> rank 1
    9 min read
  • Maximize length of the String by concatenating characters from an Array of Strings
    Find the largest possible string of distinct characters formed using a combination of given strings. Any given string has to be chosen completely or not to be chosen at all. Examples: Input: strings ="abcd", "efgh", "efgh" Output: 8Explanation: All possible combinations are {"", "abcd", "efgh", "abc
    12 min read
  • Number of strings in two array satisfy the given conditions
    Given two arrays of string arr1[] and arr2[]. For each string in arr2[](say str2), the task is to count numbers string in arr1[](say str1) which satisfy the below conditions: The first characters of str1 and str2 must be equal.String str2 must contain each character of string str1.Examples: Input: a
    14 min read
  • Check if given string can be split into four distinct strings
    Given a string, the task is to check if we can split it into 4 strings such that each string is non-empty and different from the other. Examples: Input : str[] = "geeksforgeeks"Output : Yes"geeks", "for", "gee", "ks" are four distinct strings that can form from given string.Input : str[] = "aaabb"Ou
    7 min read
  • Find the string among given strings represented using given encryption pattern
    Given an array of strings arr[] of size N and an encrypted string str, the task is to find the correct string from the given array of strings whose encryption will give str where str is encrypted using the following rules: The starting characters form an integer representing the number of uppercase
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences