VOOZH about

URL: https://www.geeksforgeeks.org/dsa/possibility-of-a-word-from-a-given-set-of-characters/

⇱ Possibility of a word from a given set of characters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Possibility of a word from a given set of characters

Last Updated : 20 Jul, 2022

Given two strings 's' and 'q', check if all characters of q are present in 's'. 

Examples: 

Example:
Input: s = "abctd"
 q = "cat"
Output: Yes
Explanation:
All characters of "cat" are
present in "abctd"
 
Input: s = dog
 hod
Output: No
Explanation:
Given query 'hod' hod has the letter
'h' which is not available in set 'dog', 
hence the output is no.

A simple solution is to try all characters one by one. Find its number of occurrences in 'q', then in 's'. Number of occurrences in 'q' must be less than or equal to same in 's'. If all characters satisfy this condition, return true. Else return false.

An efficient solution is to create a frequency array of length 256 (Number of possible characters) and initialize it to 0. Then we calculate the frequency of each element present in 's'. After counting characters in 's', we traverse through 'q' and check if frequency of each character is less than its frequency in 's', by reducing its frequency in the frequency array constructed for 's'.

Below given is the implementation of the above approach 


Output
Yes

Time complexity : O(n)
Auxiliary Space: O(256)

Comment
Article Tags: