Count of strings that can be formed from another string using each character at-most once
Last Updated :
22 Nov, 2022
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 be formed once using characters of str1.
Input: str1 = "foreeksgekseg", str2 = "geeks"
Output: 2
Approach:
Since the problem has a restriction on using characters of str1 only once to form str2. If one character has been used to form one str2, it cannot be used in forming another str2. Every character of str2 must be present in str1 at least for the formation of one str1. If all the characters of str2 are already present in str1, then the character which has the minimum occurrence in str1 will be the number of str2's that can be formed using the characters of str1 once. Below are the steps:
- Create an hash-array which stores the number of occurrences of each character of str1 and str2.
- Iterate for all the characters of str2, and find the minimum most occurrences of every character in str1.
- Return the minimum occurrence which will be the answer.
Below is the implementation of the above approach:
C++14
/// C++ program to print the number of times
// str2 can be formed from str1 using the
// characters of str1 only once
#include <bits/stdc++.h>
using namespace std;
// Function to find the number of str2
// that can be formed using characters of str1
int findNumberOfTimes(string str1, string str2)
{
int freq[26] = { 0 };
int freq2[26] = { 0 };
int l1 = str1.length();
int l2 = str2.length();
// iterate and mark the frequencies of
// all characters in str1
for (int i = 0; i < l1; i++)
freq[str1[i] - 'a'] += 1;
for (int i = 0; i < l2; i++)
freq2[str2[i] - 'a'] += 1;
int count = INT_MAX;
// find the minimum frequency of
// every character in str1
for (int i = 0; i < l2; i++)
{
if(freq2[str2[i]-'a']!=0)
count = min(count, freq[str2[i] - 'a']/freq2[str2[i]-'a']);
}
return count;
}
// Driver Code
int main()
{
string str1 = "foreeksgekseg";
string str2 = "geeks";
cout << findNumberOfTimes(str1, str2)
<< endl;
return 0;
}
Java
// Java program to print the number of times
// str2 can be formed from str1 using the
// characters of str1 only once
class GFG {
// Function to find the number of str2
// that can be formed using characters of str1
static int findNumberOfTimes(String str1, String str2)
{
int freq[] = new int[26];
int freq2[] = new int[26];
int l1 = str1.length();
// iterate and mark the frequencies of
// all characters in str1
for (int i = 0; i < l1; i++)
{
freq[str1.charAt(i) - 'a'] += 1;
}
int l2 = str2.length();
for (int i = 0; i < l2; i++)
{
freq2[str2.charAt(i) - 'a'] += 1;
}
int count = Integer.MAX_VALUE;
// find the minimum frequency of
// every character in str1
for (int i = 0; i < l2; i++)
{
if(freq2[str2.charAt(i)-'a']!=0)
count = Math.min(count,
freq[str2.charAt(i) - 'a']/freq2[str2.charAt(i)-'a']);
}
return count;
}
public static void main(String[] args) {
String str1 = "foreeksgekseg";
String str2 ="geeks";
System.out.println(findNumberOfTimes(str1, str2));
}
}
/* This code is contributed by 29AjayKumar*/
Python3
# Python3 program to print the number of
# times str2 can be formed from str1 using
# the characters of str1 only once
import sys
# Function to find the number of str2
# that can be formed using characters of str1
def findNumberOfTimes(str1, str2):
freq = [0] * 26
l1 = len(str1)
freq2= [0] * 26
l2 = len(str2)
# iterate and mark the frequencies
# of all characters in str1
for i in range(l1):
freq[ord(str1[i]) - ord("a")] += 1
for i in range(l2):
freq2[ord(str2[i]) - ord("a")] += 1
count = sys.maxsize
# find the minimum frequency of
# every character in str1
for i in range(l2):
count = min(count, freq[ord(str2[i])
- ord('a')]/freq2[ord(str2[i])-ord('a')])
return count
# Driver Code
if __name__ == '__main__':
str1 = "foreeksgekseg"
str2 = "geeks"
print(findNumberOfTimes(str1, str2))
# This code is contributed by PrinciRaj1992
C#
// C# program to print the number of
// times str2 can be formed from str1
// using the characters of str1 only once
using System;
class GFG {
// Function to find the number of
// str2 that can be formed using
// characters of str1
static int findNumberOfTimes(String str1, String str2)
{
int[] freq = new int[26];
int l1 = str1.Length;
int[] freq2 = new int[26];
int l2 = str2.Length;
// iterate and mark the frequencies
// of all characters in str1
for (int i = 0; i < l1; i++)
{
freq[str1[i] - 'a'] += 1;
}
for (int i = 0; i < l2; i++)
{
freq2[str2[i] - 'a'] += 1;
}
int count = int.MaxValue;
// find the minimum frequency of
// every character in str1
for (int i = 0; i < l2; i++)
{
if (freq2[str2[i] - 'a'] != 0)
count = Math.Min(
count, freq[str2[i] - 'a']
/ freq2[str2[i] - 'a']);
}
return count;
}
// Driver Code
public static void Main()
{
String str1 = "foreeksgekseg";
String str2 = "geeks";
Console.Write(findNumberOfTimes(str1, str2));
}
}
// This code is contributed by 29AjayKumar
PHP
<?php
// PHP program to print the number of times
// str2 can be formed from str1 using the
// characters of str1 only once
// Function to find the number of str2
// that can be formed using characters of str1
function findNumberOfTimes($str1, $str2)
{
$freq = array_fill(0, 26, NULL);
$l1 = strlen($str1);
$freq2 = array_fill(0, 26, NULL);
$l2 = strlen($str2);
// iterate and mark the frequencies
// of all characters in str1
for ($i = 0; $i < $l1; $i++)
$freq[ord($str1[$i]) - ord('a')] += 1;
for ($i = 0; $i < $l2; $i++)
$freq2[ord($str2[$i]) - ord('a')] += 1;
$count = PHP_INT_MAX;
// find the minimum frequency of
// every character in str1
for ($i = 0; $i < $l2; $i++)
$count = min($count, $freq[ord($str2[$i]) -
ord('a')]/$freq2[ord($str2[$i]) -
ord('a')]);
return $count;
}
// Driver Code
$str1 = "foreeksgekseg";
$str2 = "geeks";
echo findNumberOfTimes($str1, $str2) . "\n";
// This code is contributed by ita_c
?>
JavaScript
<script>
// Javascript program to print the number of times
// str2 can be formed from str1 using the
// characters of str1 only once
// Function to find the number of str2
// that can be formed using characters of str1
function findNumberOfTimes(str1, str2)
{
let freq = new Array(26);
let freq2 = new Array(26);
for(let i = 0; i < 26; i++)
{
freq[i] = 0;
freq2[i] = 0;
}
let l1 = str1.length;
// iterate and mark the frequencies of
// all characters in str1
for (let i = 0; i < l1; i++)
{
freq[str1[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;
}
let l2 = str2.length;
for (let i = 0; i < l2; i++)
{
freq2[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)] += 1;
}
let count = Number.MAX_VALUE;
// find the minimum frequency of
// every character in str1
for (let i = 0; i < l2; i++)
{
if(freq2[str2[i].charCodeAt(0)-'a'.charCodeAt(0)]!=0)
count = Math.min(count,
freq[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)]/freq2[str2[i].charCodeAt(0)-'a'.charCodeAt(0)]);
}
return count;
}
let str1 = "foreeksgekseg";
let str2 ="geeks";
document.write(findNumberOfTimes(str1, str2));
// This code is contributed by avanitrachhadiya2155
</script>
Complexity Analysis:
- Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively.
- Auxiliary Space: O(1)
Case: Using STL Maps with both uppercase and lowercase characters in str1 and str2.
Approach:
The operation is similar to the normal hash-array.
Here, the order does not matter. We just need to check if there are sufficient words in str1 to make str2. Traverse both strings str1 and str2 to store characters as key and their frequencies as value in maps freq1 and freq2. Divide the frequencies stored in map freq1 with frequencies that have a matching key in map freq2.
This will give us the maximum number of cycles of str2 that can be formed. Finally return minimum frequency from map freq1 which will be the final answer.
Implementation:
C++14
#include <bits/stdc++.h>
using namespace std;
int countSubStr(char* str,char* substr)
{
unordered_map<char,int>freq1;
unordered_map<char,int>freq2;
int i,mn=INT_MAX;
int l1=strlen(str);
int l2=strlen(substr);
for(i=0;i<l1;i++)
freq1[str[i]]++;
for(i=0;i<l2;i++)
freq2[substr[i]]++;
for(auto x:freq2)
mn=min(mn,freq1[x.first]/x.second);
return mn;
}
int main()
{
char str1[]= "arajjhupoot";
char str2[]="rajput";
cout<<countSubStr(str1,str2);
return 0;
}
Java
// java implementation to find sum of
// first n even numbers
import java.io.*;
import java.util.*;
class GFG
{
public static int countSubStr(String str,String substr)
{
HashMap<Character, Integer> freq1 = new HashMap<>();
HashMap<Character, Integer> freq2 = new HashMap<>();
int i, mn = Integer.MAX_VALUE;
int l1 = str.length();
int l2 = substr.length();
for(int idx = 0; idx < str.length(); idx++){
char c = str.charAt(idx);
if (freq1.containsKey(c)) {
freq1.put(c, freq1.get(c) + 1);
}
else {
freq1.put(c, 1);
}
}
for(int idx = 0; idx < substr.length(); idx++) {
char c = substr.charAt(idx);
if (freq2.containsKey(c)) {
freq2.put(c, freq2.get(c) + 1);
}
else {
freq2.put(c, 1);
}
}
for (Map.Entry mapElement : freq2.entrySet()) {
char first = (char)mapElement.getKey();
int second = (int)mapElement.getValue();
int second_f1 = freq1.get(first);
mn = Math.min(mn,second_f1/second);
}
return mn;
}
// Driver program to test above
public static void main(String[] args)
{
String str1= "arajjhupoot";
String str2="rajput";
System.out.println(countSubStr(str1,str2));
}
}
// This code is contributed by aditya942003patil
JavaScript
<script>
function countSubStr(str,substr)
{
let freq1 = new Map();
let freq2 = new Map();
let i,mn=Number.MAX_VALUE;
let l1 = str.length;
let l2 = substr.length;
for(i = 0; i < l1; i++){
if(freq1.has(str[i]) == true){
freq1.set(str[i], freq1.get(str[i]) + 1);
}
else{
freq1.set(str[i], 1);
}
}
for(i = 0; i < l2; i++){
if(freq2.has(substr[i]) == true){
freq2.set(substr[i], freq1.get(str[i]) + 1);
}
else{
freq2.set(substr[i], 1);
}
}
for(let [x, y] of freq2)
mn = Math.min(mn,Math.floor(freq1.get(x)/y));
return mn;
}
// driver code
let str1 = "arajjhupoot";
let str2 ="rajput";
document.write(countSubStr(str1,str2));
// This code is contributed by shinjanpatra
</script>
Python3
from math import floor
import sys
def countSubStr(str,substr):
freq1 = {}
freq2 = {}
mn = sys.maxsize
l1 = len(str)
l2 = len(substr)
for i in range(l1):
if(str[i] in freq1):
freq1[str[i]] = freq1[str[i]] + 1
else:
freq1[str[i]] = 1
for i in range(l2):
if substr[i] in freq2:
freq2[substr[i]] = freq1[str[i]] + 1
else:
freq2[substr[i]] = 1
for x, y in freq2.items():
mn = min(mn,floor(freq1[x]/y))
return mn
# driver code
str1 = "arajjhupoot"
str2 ="rajput"
print(countSubStr(str1,str2))
# This code is contributed by shinjanpatra
C#
using System;
using System.Collections.Generic;
class GFG {
static int countSubStr(string str, string substr)
{
Dictionary<char, int> freq1
= new Dictionary<char, int>();
Dictionary<char, int> freq2
= new Dictionary<char, int>();
int mn = Int32.MaxValue;
int l1 = str.Length;
int l2 = substr.Length;
for (int i = 0; i < l1; i++) {
if (freq1.ContainsKey(str[i])) {
var val = freq1[str[i]];
freq1.Remove(str[i]);
freq1.Add(str[i], val + 1);
}
else
freq1.Add(str[i], 1);
}
for (int i = 0; i < l2; i++) {
if (freq2.ContainsKey(substr[i])) {
var val = freq2[substr[i]];
freq2.Remove(substr[i]);
freq2.Add(substr[i], val + 1);
}
else
freq2.Add(substr[i], 1);
}
foreach(KeyValuePair<char, int> x in freq2)
{
mn = Math.Min(mn, freq1[x.Key] / x.Value);
}
return mn;
}
static void Main()
{
string str1 = "arajjhupoot";
string str2 = "rajput";
Console.Write(countSubStr(str1, str2));
}
}
Complexity Analysis:
- Time Complexity: O(l1+l2), where l1 and l2 are length of str1 and str2 respectively
- Auxiliary Space: O(1) since the total number of distinct characters in both lowercase and uppercase English alphabets is 52 (Constant).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem