Possibility of a word from a given set of characters in C++

In this problem, we are two string str1 and str2. Our task is to check whether all characters of str2 and present in str1.

Let’s take an example to understand the problem


str1 = “Hello”
str2 = “Hell”

Output − yes

Explanation − all characters of str2 are present in str1.

To solve this problem, a simple solution will be checking each character of str2 in str1 and then returning the solution.

But we need to create effective solutions. So, we will use a frequency array (length 256 for all valid characters) and then traverse str1 and increase the value in frequency array based on the corresponding character than occurred. Then we will traverse str2, which will decrease the frequency array on occurrence. And at each iteration, we will also check if this frequency has become negative. If it has then not possible otherwise it is possible.


Program to show the implementation of our solution

 Live Demo

#include <iostream>
#include <string.h>
using namespace std;
bool isPresent(string str1, string str2){
   int freq[256] = { 0 };
   for (int i = 0; i<str1.length(); i++)
   for (int i=0;i<str2.length(); i++) {
         if (freq[str2[i]] < 1)
            return false;
   return true;
int main() {
   string str1 = "tutorialspoint";
   string str2 = "point";
   cout<<"All charcters of '"<<str2<<"' are ";
   isPresent(str1,str2)?cout<<"present":cout<<"not present";
   cout<<" in '"<<str1<<"' ";
   return 0;


All charcters of 'point' are present in 'tutorialspoint'

Updated on: 17-Apr-2020


Kickstart Your Career

Get certified by completing the course

Get Started