Given a dictionary and a list of letters find all valid words that can be built with the letters

前端 未结 12 869
闹比i
闹比i 2021-01-31 12:26

The brute force way can solve the problem in O(n!), basically calculating all the permutations and checking the results in a dictionary. I am looking for ways to improve the com

12条回答
  •  别那么骄傲
    2021-01-31 12:50

    Following is more efficient way :-

    1.Use count sort to count all letters appearing in the a word in dictionary.
    2.Do count sort on the collection of letter that you are given. 
    3.Compare if the counts are same then the word can be made.
    4. Do this for all words in dictionary.
    

    This will be inefficient for multiple such queries so you can do following :-

    1. make a tupple for each word using count sort.
    2. put the tupple in a Tree or hashmap with count entries.
    3. When query is given do count sort and lookup tupple in hashmap
    

    .

    Time complexity :-

    The above method gives O(1) time complexity for a query and O(N) time complexity for hash table construction where N is no of words in dictionary

提交回复
热议问题