Check whether second string can be formed from characters of first string - GeeksforGeeks

12 May, 2021
Given two strings str1 and str2, check if str2 can be formed from str1Example :  
Input : str1 = geekforgeeks, str2 = geeks
Output : Yes
Here, string2 can be formed from string1.

Input : str1 = geekforgeeks, str2 = and
Output :  No
Here string2 cannot be formed from string1.

Input : str1 = geekforgeeks, str2 = geeeek
Output :  Yes
Here string2 can be formed from string1
as string1 contains 'e' comes 4 times in
string2 which is present in string1. 
 
The idea is to count frequencies of characters of str1 in a count array. Then traverse str2 and decrease frequency of characters of str2 in the count array. If frequency of a characters becomes negative at any point, return false.Below is the implementation of above approach :  
C++
Java
Python3
C#
PHP
Javascript
// CPP program to check whether second string// can be formed from first string#include <bits/stdc++.h>using namespace std;const int MAX = 256; bool canMakeStr2(string str1, string str2){    // Create a count array and count frequencies    // characters in str1.    int count[MAX] = {0};    for (int i = 0; i < str1.length(); i++)        count[str1[i]]++;             // Now traverse through str2 to check    // if every character has enough counts    for (int i = 0; i < str2.length(); i++)    {        if (count[str2[i]] == 0)           return false;        count[str2[i]]--;    }    return true;} // Driver Codeint main(){    string str1 = "geekforgeeks";    string str2 = "for";    if (canMakeStr2(str1, str2))       cout << "Yes";    else       cout << "No";    return 0;}
// Java program to check whether second string// can be formed from first string  class GFG {      static int MAX = 256;      static boolean canMakeStr2(String str1, String str2)    {        // Create a count array and count frequencies        // characters in str1.        int[] count = new int[MAX];        char []str3 = str1.toCharArray();        for (int i = 0; i < str3.length; i++)            count[str3[i]]++;          // Now traverse through str2 to check        // if every character has enough counts                 char []str4 = str2.toCharArray();        for (int i = 0; i < str4.length; i++) {            if (count[str4[i]] == 0)                return false;            count[str4[i]]--;        }        return true;    }      // Driver Code    static public void main(String []args)    {        String str1 = "geekforgeeks";        String str2 = "for";        if (canMakeStr2(str1, str2))            System.out.println("Yes");        else            System.out.println("No");    }}
# Python program to check whether second string# can be formed from first stringdef canMakeStr2(s1, s2):     # Create a count array and count    # frequencies characters in s1    count = {s1[i] : 0 for i in range(len(s1))}         for i in range(len(s1)):        count[s1[i]] += 1         # Now traverse through str2 to check    # if every character has enough counts    for i in range(len(s2)):        if (count.get(s2[i]) == None or count[s2[i]] == 0):            return False        count[s2[i]] -= 1    return True # Driver Codes1 = "geekforgeeks"s2 = "for" if canMakeStr2(s1, s2):    print("Yes")else:    print("No")
// C# program to check whether second string// can be formed from first stringusing System; class GFG {     static int MAX = 256;     static bool canMakeStr2(string str1, string str2)    {        // Create a count array and count frequencies        // characters in str1.        int[] count = new int[MAX];        for (int i = 0; i < str1.Length; i++)            count[str1[i]]++;         // Now traverse through str2 to check        // if every character has enough counts        for (int i = 0; i < str2.Length; i++) {            if (count[str2[i]] == 0)                return false;            count[str2[i]]--;        }        return true;    }     // Driver Code    static public void Main()    {        string str1 = "geekforgeeks";        string str2 = "for";        if (canMakeStr2(str1, str2))            Console.WriteLine("Yes");        else            Console.WriteLine("No");    }} // This code is contributed by vt_m.
<?php// PHP program to check whether// second string can be formed// from first string$MAX = 256; function canMakeStr2($str1, $str2){    // Create a count array and    // count frequencies characters    // in str1.    $count = (0);    for ($i = 0; $i < strlen($str1); $i++)         // Now traverse through str2    // to check if every character    // has enough counts    for ($i = 0; $i < strlen($str2); $i++)    {        if ($count[$str2[$i]] == 0)        return -1;    }    return true;} // Driver Code$str1 = "geekforgeeks";$str2 = "for";if (canMakeStr2($str1, $str2))echo "Yes";elseecho "No"; // This code is contributed by ajit?>
<script>    // Javascript program to check whether second string    // can be formed from first string         let MAX = 256;       function canMakeStr2(str1, str2)    {        // Create a count array and count frequencies        // characters in str1.        let count = new Array(MAX);        count.fill(0);        for (let i = 0; i < str1.length; i++)            count[str1[i]]++;           // Now traverse through str2 to check        // if every character has enough counts        for (let i = 0; i < str2.length; i++) {            if (count[str2[i]] == 0)                return false;            count[str2[i]]--;        }        return true;    }         let str1 = "geekforgeeks";    let str2 = "for";    if (canMakeStr2(str1, str2))      document.write("Yes");    else      document.write("No");             </script>
Yes
Output :  
Yes
 
YouTubeGeeksforGeeks500K subscribersCheck whether second string can be formed from characters of first string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=2J9r0lvAQjI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
jit_t
ukasp
mohit kumar 29
nidhi_biet
mukesh07
atarax
frequency-counting
Arrays
Strings
Technical Scripter
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Arrays
Maximum and minimum of an array using minimum number of comparisons
Multidimensional Arrays in Java
Queue | Set 1 (Introduction and Array Implementation)
Linked List vs Array
Reverse a string in Java
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
Python program to check if a string is palindrome or not