VOOZH about

URL: https://www.geeksforgeeks.org/dsa/print-list-items-containing-all-characters-of-a-given-word/

⇱ Print list items containing all characters of a given word - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print list items containing all characters of a given word

Last Updated : 10 Mar, 2023

There is a list of items. Given a specific word, e.g., "sun", print out all the items in list which contain all the characters of "sun". 
For example if the given word is "sun" and the items are "sunday", "geeksforgeeks", "utensils", ""just" and "sss", then the program should print "sunday" and "utensils".

Algorithm: Thanks to geek4u for suggesting this algorithm. 

1) Initialize a binary map:
 map[256] = {0, 0, ..}
2) Set values in map[] for the given word "sun"
 map['s'] = 1, map['u'] = 1, map['n'] = 1
3) Store length of the word "sun":
 len = 3 for "sun"
4) Pick words (or items)one by one from the list
 a) set count = 0;
 b) For each character ch of the picked word
 if(map['ch'] is set)
 increment count and unset map['ch'] 
 c) If count becomes equal to len (3 for "sun"),
 print the currently picked word.
 d) Set values in map[] for next list item
 map['s'] = 1, map['u'] = 1, map['n'] = 1

Output: 

unsorted
sunday


Time Complexity: O(n + m) where n is total number of characters in the list of items. And m = (number of items in list) * (number of characters in the given word)

Space Complexity: O(n)

Please write comments if you find any bug in above code/algorithm, or find other ways to solve the same problem
 

Comment
Article Tags:
Article Tags: