Given two strings ‘s’ and ‘q’, check if all characters of q are present in ‘s’.
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
Time complexity : O(n)
This article is contributed by Twinkl Bajaj. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Next word that does not contain a palindrome and has characters from first k
- Print list items containing all characters of a given word
- Arrangement of the characters of a word such that all vowels are at odd places
- Java program to count the characters in each word in a given sentence
- Find largest word in dictionary by deleting some characters of given string
- Find the count of sub-strings whose characters can be rearranged to form the given word
- Possibility of moving out of maze
- Longest Common Prefix using Word by Word Matching
- C program to Replace a word in a text by another given word
- Replace minimal number of characters to make all characters pair wise distinct
- Minimum number of operations to move all uppercase characters before all lower case characters
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Rearrange the characters of the string such that no two adjacent characters are consecutive English alphabets
- Min flips of continuous characters to make all characters same in a string
- String with k distinct characters and no same characters adjacent