Skip to content
Related Articles

# Check whether second string can be formed from characters of first string used any number of times

• Last Updated : 04 Aug, 2021

Given two strings str1 of size N and str2 of size M.The task is to find if it is possible to compose str2 by using only the characters of str1 such that every character of str1 can be used any number of time.
Note: Lower case letters and upper case letters should be considered different.

Examples:

Input: str1 = “The quick brown fox jumps”, str2 = “the fox was quicker than the dog”
Output: No
Explanation:
In str2, there is d character, which is not present in str1. So, it is impossible to make the string str2 from str1

Input: str1 = “we all love geeksforgeeks”, str2 = “we all love geeks”
Output: Yes

Naive Approach: The simplest approach is to search for every character of str2 in str1. If all the characters are found then print “Yes”. Otherwise print “No”.

Time Complexity: O(N*M)
Auxiliary Space: O(1)

Efficient Approach: The idea is to mark the presence of all characters of str1 in a count[] array. Then traverse str2 and check if the characters of str2 is present in str1 or not.

1. Make an array count[] of size 256 (number of total ASCII characters ) and set it to zero.
2. Then iterate over str1 and make count[str[i]] = 1 to mark the occurrence of every character.
3. Iterate over str2 and check if that character is present in str1 or not using count[] array.

Below is the implementation of the above approach:

## CPP

 `// C++ implementation of``// the above approach``#include ``using` `namespace` `std;` `// Function to check if``// str2 can be made by characters``// of str1 or not``void` `isPossible(string str1, string str2)``{``    ``// To store the``    ``// occurrence of every``    ``// character``    ``int` `arr[256] = { 0 };` `    ``// Length of the two``    ``// strings``    ``int` `l1 = str1.size();``    ``int` `l2 = str2.size();` `    ``int` `i, j;` `    ``// Assume that it is``    ``// possible to compose the``    ``// string str2 from str1``    ``bool` `possible = ``true``;` `    ``// Iterate over str1``    ``for` `(i = 0; i < l1; i++) {``        ``// Store the presence of every``        ``// character``        ``arr[str1[i]] = 1;``    ``}` `    ``// Iterate over str2``    ``for` `(i = 0; i < l2; i++) {` `        ``// Ignore the spaces``        ``if` `(str2[i] != ``' '``) {` `            ``// Check for the presence``            ``// of character in str1``            ``if` `(arr[str2[i]] == 1)``                ``continue``;` `            ``else` `{``                ``possible = ``false``;``                ``break``;``            ``}``        ``}``    ``}` `    ``// If it is possible to make``    ``// str2 from str1``    ``if` `(possible) {``        ``cout << ``"Yes"` `<< endl;``    ``}``    ``else` `{``        ``cout << ``"No"` `<< endl;``    ``}``}` `// Driver Code``int` `main()``{``    ``// Given strings``    ``string str1 = ``"we all love geeksforgeeks"``;``    ``string str2 = ``"we all love geeks"``;` `    ``// Function Call``    ``isPossible(str1, str2);``    ``return` `0;``}`

## Java

 `// Java implementation of``// the above approach` `import` `java.util.Arrays;` `class` `GFG {` `    ``// Function to check if``    ``// str2 can be made by characters``    ``// of str1 or not``    ``public` `static` `void` `isPossible(String str1, String str2) {``        ``// To store the``        ``// occurrence of every``        ``// character``        ``int` `arr[] = ``new` `int``[``256``];` `        ``Arrays.fill(arr, ``0``);``        ``// Length of the two``        ``// strings``        ``int` `l1 = str1.length();``        ``int` `l2 = str2.length();` `        ``int` `i, j;` `        ``// Assume that it is``        ``// possible to compose the``        ``// string str2 from str1``        ``boolean` `possible = ``true``;` `        ``// Iterate over str1``        ``for` `(i = ``0``; i < l1; i++) {``            ``// Store the presence of every``            ``// character``            ``arr[str1.charAt(i)] = ``1``;``        ``}` `        ``// Iterate over str2``        ``for` `(i = ``0``; i < l2; i++) {` `            ``// Ignore the spaces``            ``if` `(str2.charAt(i) != ``' '``) {` `                ``// Check for the presence``                ``// of character in str1``                ``if` `(arr[str2.charAt(i)] == ``1``)``                    ``continue``;` `                ``else` `{``                    ``possible = ``false``;``                    ``break``;``                ``}``            ``}``        ``}` `        ``// If it is possible to make``        ``// str2 from str1``        ``if` `(possible) {``            ``System.out.println(``"Yes"``);``        ``} ``else` `{``            ``System.out.println(``"No"``);``        ``}``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String args[])``    ``{``        ``// Given strings``        ``String str1 = ``"we all love geeksforgeeks"``;``        ``String str2 = ``"we all love geeks"``;` `        ``// Function Call``        ``isPossible(str1, str2);` `    ``}` `}` `// This code is contributed by saurabh_jaiswal.`

## C#

 `// C# implementation of``// the above approach``using` `System;``using` `System.Collections.Generic;` `class` `GFG{` `// Function to check if``// str2 can be made by characters``// of str1 or not``static` `void` `isPossible(``string` `str1, ``string` `str2)``{``  ` `    ``// To store the``    ``// occurrence of every``    ``// character``    ``int` `[]arr = ``new` `int``[256];``    ``Array.Clear(arr,0,256);` `    ``// Length of the two``    ``// strings``    ``int` `l1 = str1.Length;``    ``int` `l2 = str2.Length;` `    ``int` `i;` `    ``// Assume that it is``    ``// possible to compose the``    ``// string str2 from str1``    ``bool` `possible = ``true``;` `    ``// Iterate over str1``    ``for` `(i = 0; i < l1; i++) {``        ``// Store the presence of every``        ``// character``        ``arr[str1[i]] = 1;``    ``}` `    ``// Iterate over str2``    ``for` `(i = 0; i < l2; i++) {` `        ``// Ignore the spaces``        ``if` `(str2[i] != ``' '``) {` `            ``// Check for the presence``            ``// of character in str1``            ``if` `(arr[str2[i]] == 1)``                ``continue``;` `            ``else` `{``                ``possible = ``false``;``                ``break``;``            ``}``        ``}``    ``}` `    ``// If it is possible to make``    ``// str2 from str1``    ``if` `(possible) {``        ``Console.Write(``"Yes"``);``    ``}``    ``else` `{``        ``Console.Write(``"No"``);``    ``}``}` `// Driver Code``public` `static` `void` `Main()``{``    ``// Given strings``    ``string` `str1 = ``"we all love geeksforgeeks"``;``    ``string` `str2 = ``"we all love geeks"``;` `    ``// Function Call``    ``isPossible(str1, str2);``}``}` `// This code is contributed by ipg2016107.`

## Python3

 `# Python3 implementation of``# the above approach` `# Function to check if``# str2 can be made by characters``# of str1 or not``def` `isPossible(str1, str2):``  ` `      ``# To store the``    ``# occurrence of every``    ``# character``    ``arr ``=` `{}``    ` `    ``# Length of the two``    ``# strings``    ``l1 ``=` `len``(str1)``    ``l2 ``=` `len``(str2)``    ` `        ``# Assume that it is``    ``# possible to compose the``    ``# string str2 from str1``    ``possible ``=` `True``    ` `        ``# Iterate over str1``    ``for` `i ``in` `range``(l1):``      ` `      ``# Store the presence or every element``        ``arr[str1[i]] ``=` `1``        ` `        ``# Iterate over str2``    ``for` `i ``in` `range``(l2):``      ` `      ``# Ignore the spaces``        ``if` `str2[i] !``=` `' '``:``          ` `              ``# Check for the presence``           ``# of character in str1``            ``if` `arr[str2[i]] ``=``=` `1``:``                ``continue``            ``else``:``                ``possible ``=` `False``                ``break``                ` `     ``# If it is possible to make``    ``# str2 from str1          ``    ``if` `possible:``        ``print``(``"Yes"``)``    ``else``:``        ``print``(``"No"``)`  `# Driver code``str1 ``=` `"we all love geeksforgeeks"``str2 ``=` `"we all love geeks"` `# Function call.``isPossible(str1, str2)` `# This code is contributed by Parth Manchanda`

## Javascript

 ``
Output:
`Yes`

Time Complexity: O(N+M)
Auxiliary Space: O(1)

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.

My Personal Notes arrow_drop_up