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 Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
C++ Program for Minimum move to end operations to make all strings equal
Next article icon

C++ Program for Check if given string can be formed by two other strings or their permutations

Last Updated : 23 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string str and an array of strings arr[], the task is to check if the given string can be formed by any of the string pair from the array or their permutations. 
Examples:

Input: str = “amazon”, arr[] = {“loa”, “azo”, “ft”, “amn”, “lka”} 
Output: Yes The chosen strings are “amn” and “azo” which can be rearranged as “amazon”.

 Input: str = “geeksforgeeks”, arr[] = {“geeks”, “geek”, “for”} 
Output: No

Method 1: In this approach, we begin by sorting the given string, then we run two nested loops to select two strings from the given array at a time and concatenate them. Then we sort the resultant string which we got after concatenation.
We then compare this string with the given string and check if they are equal or not. If found equal we return true.

Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that returns true if str can be
// generated from any permutation of the
// two strings selected from the given vector
bool isPossible(vector<string> v, string str)
{
 
    // Sort the given string
    sort(str.begin(), str.end());
 
    // Select two strings at a time from given vector
    for (int i = 0; i < v.size() - 1; i++) {
        for (int j = i + 1; j < v.size(); j++) {
 
            // Get the concatenated string
            string temp = v[i] + v[j];
 
            // Sort the resultant string
            sort(temp.begin(), temp.end());
 
            // If the resultant string is equal
            // to the given string str
            if (temp.compare(str) == 0) {
                return true;
            }
        }
    }
 
    // No valid pair found
    return false;
}
 
// Driver code
int main()
{
    string str = "amazon";
    vector<string> v{ "fds", "oxq", "zoa", "epw", "amn" };
 
    if (isPossible(v, str))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}
 
 
Output
Yes

Time complexity: O(nlogn+m2klogk) where n is the size of the given string, m is the size of the given array, and k is the maximum size obtained by adding any two strings (which is basically the sum of the size of the two longest strings in the given array).

Space Complexity: O(n) as tmp string has been created. Here n is maximum possible length of tmp string .

Method 2: Counting sort can be used to reduce the running time of the above approach. Counting sort uses a table to store the count of each character. We have 26 alphabets hence we make an array of size 26 to store counts of each character in the string. Then take the characters in increasing order to get the sorted string. Below is the implementation of the above approach: 

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
#define MAX 26
 
// Function to sort the given string
// using counting sort
void countingsort(string& s)
{
    // Array to store the count of each character
    int count[MAX] = { 0 };
    for (int i = 0; i < s.length(); i++) {
        count[s[i] - 'a']++;
    }
    int index = 0;
 
    // Insert characters in the string
    // in increasing order
    for (int i = 0; i < MAX; i++) {
        int j = 0;
        while (j < count[i]) {
            s[index++] = i + 'a';
            j++;
        }
    }
}
 
// Function that returns true if str can be
// generated from any permutation of the
// two strings selected from the given vector
bool isPossible(vector<string> v, string str)
{
 
    // Sort the given string
    countingsort(str);
 
    // Select two strings at a time from given vector
    for (int i = 0; i < v.size() - 1; i++) {
        for (int j = i + 1; j < v.size(); j++) {
 
            // Get the concatenated string
            string temp = v[i] + v[j];
 
            // Sort the resultant string
            countingsort(temp);
 
            // If the resultant string is equal
            // to the given string str
            if (temp.compare(str) == 0) {
                return true;
            }
        }
    }
 
    // No valid pair found
    return false;
}
 
// Driver code
int main()
{
    string str = "amazon";
    vector<string> v{ "fds", "oxq", "zoa", "epw", "amn" };
 
    if (isPossible(v, str))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}
 
 
Output
Yes

Time complexity: O(n+m2k) where n is the size of the given string, m is the size of the given array, and k is the maximum size obtained by adding any two strings (which is basically the sum of the size of the two longest strings in the given array).

Auxiliary Space: O(x) where x is the maximum length of two input strings after concatenating

Please refer complete article on Check if given string can be formed by two other strings or their permutations for more details!



Next Article
C++ Program for Minimum move to end operations to make all strings equal
author
kartik
Improve
Article Tags :
  • Arrays
  • C++ Programs
  • DSA
  • Searching
  • Sorting
  • Strings
  • counting-sort
Practice Tags :
  • Arrays
  • Searching
  • Sorting
  • Strings

Similar Reads

  • C Program to check if two given strings are isomorphic to each other
    Given two strings str1 and str2, the task is to check if the two given strings are isomorphic to each other or not. Two strings are said to be isomorphic if there is a one to one mapping possible for every character of str1 to every character of str2 and all occurrences of every character in str1 ma
    2 min read
  • C++ Program to Check if a string can be obtained by rotating another string d places
    Given two strings str1 and str2 and an integer d, the task is to check whether str2 can be obtained by rotating str1 by d places (either to the left or to the right). Examples: Input: str1 = "abcdefg", str2 = "cdefgab", d = 2 Output: Yes Rotate str1 2 places to the left. Input: str1 = "abcdefg", str
    4 min read
  • C++ Program for Minimum move to end operations to make all strings equal
    Given n strings that are permutations of each other. We need to make all strings same with an operation that takes front character of any string and moves it to the end.Examples: Input : n = 2 arr[] = {"molzv", "lzvmo"} Output : 2 Explanation: In first string, we remove first element("m") from first
    3 min read
  • C++ Program to check if strings are rotations of each other or not
    Given a string s1 and a string s2, write a snippet to say whether s2 is a rotation of s1? (eg given s1 = ABCD and s2 = CDAB, return true, given s1 = ABCD, and s2 = ACBD , return false) Algorithm: areRotations(str1, str2) 1. Create a temp string and store concatenation of str1 to str1 in temp. temp =
    2 min read
  • C++ Program to Check if strings are rotations of each other or not | Set 2
    Given two strings s1 and s2, check whether s2 is a rotation of s1. Examples:  Input : ABACD, CDABA Output : True Input : GEEKS, EKSGE Output : True We have discussed an approach in earlier post which handles substring match as a pattern. In this post, we will be going to use KMP algorithm's lps (lon
    2 min read
  • Check if the given string of words can be formed from words present in the dictionary
    Given a string array of M words and a dictionary of N words. The task is to check if the given string of words can be formed from words present in the dictionary. Examples: dict[] = { find, a, geeks, all, for, on, geeks, answers, inter } Input: str[] = { "find", "all", "answers", "on", "geeks", "for
    15+ min read
  • C++ Program to Check if a string can be obtained by rotating another string 2 places
    Given two strings, the task is to find if a string can be obtained by rotating another string two places. Examples: Input: string1 = "amazon", string2 = "azonam" Output: Yes // rotated anti-clockwiseInput: string1 = "amazon", string2 = "onamaz" Output: Yes // rotated clockwise Asked in: Amazon Inter
    2 min read
  • C++ Program to Check if a string can be formed from another string by at most X circular clockwise shifts
    Given an integer X and two strings S1 and S2, the task is to check that string S1 can be converted to the string S2 by shifting characters circular clockwise atmost X times. Input: S1 = "abcd", S2 = "dddd", X = 3 Output: Yes Explanation: Given string S1 can be converted to string S2 as- Character "a
    3 min read
  • Iterative program to generate distinct Permutations of a String
    Given a string str, the task is to generate all the distinct permutations of the given string iteratively. Examples: Input: str = "bba" Output: abb bab bba Input: str = "abc" Output: abc acb bac bca cab cba Approach: The number of permutations for a string of length n are n!. The following algorithm
    15+ min read
  • Find the number of strings formed using distinct characters of a given string
    Given a string str consisting of lowercase English alphabets, the task is to find the count of all possible string of maximum length that can be formed using the characters of str such that no two characters in the generated string are same.Examples: Input: str = "aba" Output: 2 "ab" and "ba" are th
    4 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