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:
Remove characters from the first string which are present in the second string
Next article icon

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

Last Updated : 29 Sep, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two strings str1 and str2, check if str2 can be formed from str1

Example : 

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++
// 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 Code int main() {     string str1 = "geekforgeeks";     string str2 = "for";     if (canMakeStr2(str1, str2))        cout << "Yes";     else        cout << "No";     return 0; } 
Java
// 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");     } }    
Python3
# Python program to check whether second string # can be formed from first string def 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 Code s1 = "geekforgeeks" s2 = "for"  if canMakeStr2(s1, s2):     print("Yes") else:     print("No") 
C#
// C# program to check whether second string // can be formed from first string using 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 // 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"; else echo "No";  // This code is contributed by ajit ?> 
JavaScript
<script>   // Javascript program to check whether second string   // can be formed from first string    function canMakeStr2(str1, str2)   {       // Create a count array and count frequencies       // characters in str1.       let count = {};       //         count.fill(0);       for (let i = 0; i < str1.length; i++) {           if (str1[i] in count)               count[str1[i]]++;           else               count[str1[i]] = 1       }        // 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 || !(str2[i] in count))               return false;           count[str2[i]]--;       }       return true;   }    let str1 = "geekforgeeks";   let str2 = "gggeek";   if (canMakeStr2(str1, str2))       document.write("Yes");   else       document.write("No"); </script> 

Output
Yes

Time Complexity: O(n+m), where n and m are the length of the given strings. 
Auxiliary Space: O(256), which is constant.


Next Article
Remove characters from the first string which are present in the second string

A

anuragrawat1
Improve
Article Tags :
  • Misc
  • Strings
  • Technical Scripter
  • DSA
  • Arrays
  • frequency-counting
Practice Tags :
  • Arrays
  • Misc
  • Strings

Similar Reads

  • Count of times second string can be formed from the characters of first string
    Given two strings str and patt, the task is to find the count of times patt can be formed using the characters of str. Examples: Input: str = "geeksforgeeks", patt = "geeks" Output: 2 "geeks" can be made at most twice from the characters of "geeksforgeeks". Input: str = "abcbca", patt = "aabc" Outpu
    6 min read
  • Check if characters of one string can be swapped to form other
    Two strings are given, we need to find whether we can form second string by swapping the character of the first string. Examples: Input : str1 = "geeksforgeeks" str2 = "geegeeksksfor" Output : YES Input : str1 = "geeksfor" str2 = "geeekfor" Output : NO First of all, we will find the length of string
    6 min read
  • Check if String formed by first and last X characters of a String is a Palindrome
    Given a string str and an integer X. The task is to find whether the first X characters of both string str and reversed string str are same or not. If it is equal then print true, otherwise print false. Examples: Input: str = abcdefba, X = 2Output: trueExplanation: First 2 characters of both string
    5 min read
  • Remove characters from the first string which are present in the second string
    Given two strings string1 and string2, remove those characters from the first string(string1) which are present in the second string(string2). Both strings are different and contain only lowercase characters.NOTE: The size of the first string is always greater than the size of the second string( |st
    15+ min read
  • Check if String T can be made Substring of S by replacing given characters
    Given two strings S and T and a 2D array replace[][], where replace[i] = {oldChar, newChar} represents that the character oldChar of T is replaced with newChar. The task is to find if it is possible to make string T a substring of S by replacing characters according to the replace array. Note: Each
    9 min read
  • Check if a string can be split into two strings with same number of K-frequent characters
    Given a string S and an integer K, the task is to check if it is possible to distribute these characters into two strings such that the count of characters having a frequency K in both strings is equal. If it is possible, then print a sequence consisting of 1 and 2, which denotes which character sho
    11 min read
  • Count of strings that can be formed from another string using each character at-most once
    Given two strings str1 and str2, the task is to print the number of times str2 can be formed using characters of str1. However, a character at any index of str1 can only be used once in the formation of str2. Examples: Input: str1 = "arajjhupoot", str2 = "rajput" Output: 1 Explanation:str2 can only
    10 min read
  • Check if string S can be converted to T by incrementing characters
    Given strings S and T. The task is to check if S can be converted to T by performing at most K operations. For the ith operation, select any character in S which has not been selected before, and increment the chosen character i times (i.e., replacing it with the letter i times ahead in the alphabet
    8 min read
  • Check if both halves of the string have same set of characters
    Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the
    12 min read
  • Check if a two character string can be made using given words
    Given a string of two characters and n distinct words of two characters. The task is to find if it is possible to arrange given words in such a way that the concatenated string has the given two character string as a substring. We can append a word multiple times. Examples: Input : str = "ya" words[
    6 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