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:
Count Occurrences of a Given Character in a String
Next article icon

Count occurrences of a string that can be constructed from another given string

Last Updated : 15 Dec, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given two strings str1 and str2 where str1 being the parent string. The task is to find out the number of string as str2 that can be constructed using letters of str1. 

Note: All the letters are in lowercase and each character should be used only once.

Examples: 

Input: str1 = "geeksforgeeks", str2 = "geeks" Output: 2  Input: str1 = "geekgoinggeeky", str2 = "geeks" Output: 0

Approach: Store the frequency of characters of str2 in hash2, and do the same for str1 in hash1. Now, find out the minimum value of hash1[i]/hash2[i] for all i where hash2[i]>0.

Below is the implementation of the above approach: 

C++




// C++ implementation of the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the count
int findCount(string str1, string str2)
{
    int len = str1.size();
    int len2 = str2.size();
    int ans = INT_MAX;
 
    // Initialize hash for both strings
    int hash1[26] = { 0 }, hash2[26] = { 0 };
 
    // hash the frequency of letters of str1
    for (int i = 0; i < len; i++)
        hash1[str1[i] - 'a']++;
 
    // hash the frequency of letters of str2
    for (int i = 0; i < len2; i++)
        hash2[str2[i] - 'a']++;
 
    // Find the count of str2 constructed from str1
    for (int i = 0; i < 26; i++)
        if (hash2[i])
            ans = min(ans, hash1[i] / hash2[i]);
 
    // Return answer
    return ans;
}
 
// Driver code
int main()
{
    string str1 = "geeksclassesatnoida";
    string str2 = "sea";
    cout << findCount(str1, str2);
 
    return 0;
}
 
 

Java




// Java implementation of the above approach
import java.io.*;
public class GFG
{
    // Function to find the count
    static int findCount(String str1, String str2)
    {
        int len = str1.length();
        int len2 = str2.length();
        int ans = Integer.MAX_VALUE;
     
        // Initialize hash for both strings
        int [] hash1 = new int[26];
        int [] hash2 = new int[26];
     
        // hash the frequency of letters of str1
        for (int i = 0; i < len; i++)
            hash1[(int)(str1.charAt(i) - 'a')]++;
     
        // hash the frequency of letters of str2
        for (int i = 0; i < len2; i++)
            hash2[(int)(str2.charAt(i) - 'a')]++;
     
        // Find the count of str2 constructed from str1
        for (int i = 0; i < 26; i++)
            if (hash2[i] != 0)
                ans = Math.min(ans, hash1[i] / hash2[i]);
     
        // Return answer
        return ans;
    }
     
    // Driver code
    public static void main(String []args)
    {
        String str1 = "geeksclassesatnoida";
        String str2 = "sea";
        System.out.println(findCount(str1, str2));
    }
}
 
// This code is contributed by ihritik
 
 

Python3




# Python3 implementation of the above approach
 
import sys
 
# Function to find the count
def findCount(str1, str2):
 
    len1 = len(str1)
    len2 = len(str2)
    ans = sys.maxsize
 
    # Initialize hash for both strings
    hash1 = [0] * 26
    hash2 = [0] * 26
 
    # hash the frequency of letters of str1
    for i in range(0, len1):
        hash1[ord(str1[i]) - 97] = hash1[ord(str1[i]) - 97] + 1
 
    # hash the frequency of letters of str2
    for i in range(0, len2):
        hash2[ord(str2[i]) - 97] = hash2[ord(str2[i]) - 97] + 1
         
    # Find the count of str2 constructed from str1
    for i in range (0, 26):
        if (hash2[i] != 0):
            ans = min(ans, hash1[i] // hash2[i])
 
    # Return answer
    return ans
 
     
# Driver code
str1 = "geeksclassesatnoida"
str2 = "sea"
print(findCount(str1, str2))
 
# This code is contributed by ihritik
 
 

C#




// C# implementation of the above approach
using System;
 
class GFG
{
    // Function to find the count
    static int findCount(string str1, string str2)
    {
        int len = str1.Length;
        int len2 = str2.Length;
        int ans = Int32.MaxValue;
     
        // Initialize hash for both strings
        int [] hash1 = new int[26];
        int [] hash2 = new int[26];
     
        // hash the frequency of letters of str1
        for (int i = 0; i < len; i++)
            hash1[str1[i] - 'a']++;
     
        // hash the frequency of letters of str2
        for (int i = 0; i < len2; i++)
            hash2[str2[i] - 'a']++;
     
        // Find the count of str2 constructed from str1
        for (int i = 0; i < 26; i++)
            if (hash2[i] != 0)
                ans = Math.Min(ans, hash1[i] / hash2[i]);
     
        // Return answer
        return ans;
    }
     
    // Driver code
    public static void Main()
    {
        string str1 = "geeksclassesatnoida";
        string str2 = "sea";
        Console.WriteLine(findCount(str1, str2));
    }
}
 
// This code is contributed by ihritik
 
 

PHP




<?php
// PHP implementation of the above approach
 
// Function to find the count
function findCount($str1, $str2)
{
    $len = strlen($str1) ;
    $len2 = strlen($str1);
    $ans = PHP_INT_MAX;
 
    // Initialize hash for both strings
    $hash1 = array_fill(0, 26, 0) ;
    $hash2 = array_fill(0, 26, 0);
 
    // hash the frequency of letters of str1
    for ($i = 0; $i < $len; $i++)
        $hash1[ord($str1[$i]) - ord('a')]++;
 
    // hash the frequency of letters of str2
    for ($i = 0; $i < $len2; $i++)
        $hash2[ord($str2[$i]) - ord('a')]++;
 
    // Find the count of str2 constructed from str1
    for ($i = 0; $i < 26; $i++)
        if ($hash2[$i])
            $ans = min($ans, $hash1[$i] / $hash2[$i]);
 
    // Return answer
    return $ans;
}
 
    // Driver code
    $str1 = "geeksclassesatnoida";
    $str2 = "sea";
    echo findCount($str1, $str2);
     
// This code is contributed by Ryuga
?>
 
 

Javascript




<script>
      // JavaScript implementation of the above approach
 
      // Function to find the count
      function findCount(str1, str2) {
        var len = str1.length;
        var len2 = str2.length;
        //MAX Integer Value
        var ans = 21474836473;
 
        // Initialize hash for both strings
        var hash1 = new Array(26).fill(0);
        var hash2 = new Array(26).fill(0);
 
        // hash the frequency of letters of str1
        for (var i = 0; i < len; i++)
          hash1[str1[i].charCodeAt(0) - "a".charCodeAt(0)]++;
 
        // hash the frequency of letters of str2
        for (var i = 0; i < len2; i++)
          hash2[str2[i].charCodeAt(0) - "a".charCodeAt(0)]++;
 
        // Find the count of str2 constructed from str1
        for (var i = 0; i < 26; i++)
          if (hash2[i]) ans = Math.min(ans, hash1[i] / hash2[i]);
 
        // Return answer
        return ans;
      }
 
      // Driver code
      var str1 = "geeksclassesatnoida";
      var str2 = "sea";
      document.write(findCount(str1, str2));
    </script>
 
 
Output
3

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(1)


Next Article
Count Occurrences of a Given Character in a String

S

Shivam.Pradhan
Improve
Article Tags :
  • DSA
  • Hash
  • Pattern Searching
  • Strings
  • frequency-counting
Practice Tags :
  • Hash
  • Pattern Searching
  • Strings

Similar Reads

  • Count occurrences of strings formed using words in another string
    Given a string A and a vector of strings B, the task is to count the number of strings in vector B that only contains the words from A. Examples: Input: A="blue green red yellow"B[]={"blue red", "green pink", "yellow green"}Output: 2 Input: A="apple banana pear"B[]={"apple", "banana apple", "pear ba
    7 min read
  • Count Occurrences of a Given Character in a String
    Given a string S and a character 'c', the task is to count the occurrence of the given character in the string. Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str. Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times i
    6 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
  • 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
  • Count of strings that does not contain any character of a given string
    Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
    8 min read
  • Count of strings that can be formed using a, b and c under given constraints
    Given a length n, count the number of strings of length n that can be made using 'a', 'b' and 'c' with at most one 'b' and two 'c's allowed. Examples : Input : n = 3 Output : 19 Below strings follow given constraints: aaa aab aac aba abc aca acb acc baa bac bca bcc caa cab cac cba cbc cca ccb Input
    14 min read
  • Check if a string can be repeated to make another string
    Given two strings a and b, the task is to check how many times the string a can be repeated to generate the string b. If b cannot be generated by repeating a then print -1. Examples: Input: a = "geeks", b = "geeksgeeks" Output: 2 "geeks" can be repeated twice to generate "geeksgeeks" Input: a = "df"
    9 min read
  • Check if characters of a given string can be used to form any N equal strings
    Given a string S and an integer N, the task is to check if it is possible to generate any string N times from the characters of the given string or not. If it is possible, print Yes. Otherwise, print No. Examples: Input: S = "caacbb", N = 2Output: YesExplanation: All possible strings that can be gen
    5 min read
  • Count occurrences of a character in a repeated string
    Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.Examples: Input : N = 10 str = "abcac"Output : 4Explanation: "abcacabcac" is the substring from the infinitely repeated string. In first
    8 min read
  • Count of substrings of a string containing another given string as a substring
    Given two strings S and T, the task is to count the number of substrings of S that contains string T in it as a substring. Examples: Input: S = "dabc", T = "ab"Output: 4Explanation: Substrings of S containing T as a substring are: S[0, 2] = “dab”S[1, 2] = “ab”S[1, 3] = “abc”S[0, 3] = “dabc” Input: S
    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