Problem
Given a list of words
, list of single letters
(might be repeating) and score
of every character.
Return the maximum score of any valid set of words formed by using the given letters (words[i]
cannot be used two or more times).
It is not necessary to use all characters in letters
and each letter can only be used once. Score of letters 'a'
, 'b'
, 'c'
, … ,'z'
is given by score[0]
, score[1]
, … , score[25]
respectively.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Solution
Method 1 - Backtracking
We start in a similar way to Subsets, and try to form set of words.
Here is the video explanation:
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n*l*2^n)
-n
- number of words,l
- average length of the words. (We also change count array, but that multiplies time complexity by 26, which is constant). - 🧺 Space complexity:
O(n)
Dry Run
We start first by creating frequency map (count
array) for given letters
. count
array initially: {'a': 2, 'c': 1, 'd': 3, 'g': 1, 'o': 2}
.
Lets calculate the score of each word, for our understanding, assuming we are able to form it:
idx = 0
, Word = “dog”
- “dog” can be formed using
{'d': 1, 'o': 1, 'g': 1}
- Score: 5 + 2 + 3 = 10
count = {'a': 2, 'c': 1, 'd': 2, 'g': 0, 'o': 1}
idx = 1
, Word = “cat”
- “cat” cannot be formed (not enough ’t’), so we skip
idx = 2
, Word = “dad”
- “dad” can be formed using
{'d': 2, 'a': 1}
- Score: 5 + 1 + 5 = 11.
count = {'a': 1, 'c': 1, 'd': 1, 'g': 1, 'o': 2}
idx = 3
, Word = “good”
- “good” can be formed using {‘g’: 1, ‘o’: 2, ’d’: 1}
- Score: 3 + 0 + 0 + 3 = 6
count = {'a': 2, 'c': 1, 'd': 2, 'g': 0, 'o': 0}
Recursive depth from different levels
We start with idx = 0
.
We now start DFS on words = ["dog","cat","dad","good"]
.