Python 1255.py
class Solution:
def maxScoreWords(self, words: List[str], letters: List[str], score: List[int]) -> int:
def deeper(pos, available):
if pos == len(words):
return 0
# ignore this word
skip = deeper(pos + 1, available)
# use this word
gain = 0
have = available.copy()
for c in words[pos]:
# not enough letters ?
if c not in have or have[c] == 0:
return skip
have[c] -= 1
gain += score[ord(c) - ord("a")]
# use higher score
return max(skip, gain + deeper(pos + 1, have))
abc = defaultdict(int)
for l in letters:
abc[l] += 1
return deeper(0, abc)
Difficulty
and has an acceptance rate of about 82% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- Bitmask
- Counting
- Dynamic Programming
- Hash Table
- String
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the problem of selecting a subset of words that yields the maximum total score while respecting a limited supply of letters. It builds a frequency map of the available letters, then explores all possible inclusion/exclusion decisions for each word using a depth-first recursion. The recursion returns the best achievable score from the current position onward, given the remaining letters.
Core Components
Frequency Map Construction
abc = defaultdict(int)
for l in letters:
abc[l] += 1
A defaultdict of integers records how many times each letter appears in the input letters. This map serves as the mutable resource that the recursive routine consumes.
Recursive Exploration
def deeper(pos, available):
if pos == len(words):
return 0
# ignore this word
skip = deeper(pos + 1, available)
# use this word
gain = 0
have = available.copy()
for c in words[pos]:
# not enough letters ?
if c not in have or have[c] == 0:
return skip
have[c] -= 1
gain += score[ord(c) - ord("a")]
# use higher score
return max(skip, gain + deeper(pos + 1, have))
The function deeper receives the index of the current word (pos) and a dictionary available that reflects the letters still usable. The base case terminates when all words have been considered, returning a score of zero.
Two branches are evaluated:
- Skip branch - the word at
posis ignored, and the recursion proceeds with the sameavailablemap. - Take branch - the algorithm attempts to consume the letters required by the current word. A copy of
available(have) is created so that modifications do not affect the skip branch. While iterating over the characters ofwords[pos], the code checks whether each character is present and has a positive count. If any character is missing, the function abandons the take branch and returns the result of the skip branch immediately. Otherwise, the character count is decremented and the corresponding score is added togain. After successfully processing the whole word, the recursion continues with the updatedhave, and the total score for this branch becomesgain + deeper(pos + 1, have).
Finally, the function returns the larger of the two branch results, ensuring that the optimal choice is propagated upward.
Entry Point
return deeper(0, abc)
The recursion starts at the first word with the full letter inventory.
Edge Cases Handled
When a word contains a character that is not present in the current available map, the inner loop detects the missing letter (c not in have or have[c] == 0) and aborts the take branch, falling back to the skip result. This prevents attempts to use unavailable letters and automatically handles words that require more copies of a letter than are supplied.
If the input words list is empty, the initial call to deeper reaches the base case immediately, returning zero, which correctly reflects that no score can be earned.
An empty letters list yields an abc map with no entries; any non-empty word will fail the availability check, causing every recursive branch to skip the word, and the final result will be zero.
Repeated letters in letters are counted correctly by the frequency map, and the decrement operation (have[c] -= 1) ensures that each occurrence is consumed only once per word usage.
Words that consist solely of letters present in sufficient quantity are processed fully, accumulating their scores via gain += score[ord(c) - ord("a")]. The use of ord maps each character to its index in the score list without additional lookups.
Performance Optimizations
The algorithm incorporates several techniques that reduce unnecessary work:
-
Early pruning - As soon as a required character is missing, the function returns the skip branch result without exploring deeper recursion for the current word. This prevents the exponential blow-up that would occur if every word were fully examined regardless of feasibility.
-
Selective copying - The
availabledictionary is copied only when the algorithm decides to attempt using the current word. The skip branch reuses the original dictionary, avoiding the overhead of copying on every recursive call. -
Direct score indexing - By converting a character to its alphabet position with
ord(c) - ord("a"), the code accesses the corresponding score in constant time, eliminating the need for auxiliary mappings. -
Immutable recursion state - The recursion passes a fresh dictionary (
have) to the next level when a word is taken, guaranteeing that sibling branches do not interfere with each other’s state. This design avoids the cost of deep cloning the entire state tree and keeps each branch’s modifications localized. -
Tail-like recursion pattern - The function computes the result for the current position before delegating to the next position, allowing the Python interpreter to reuse stack frames efficiently for the skip branch when the take branch is pruned early.
These choices collectively keep the search space as small as possible while preserving correctness, enabling the solution to handle moderate input sizes within practical runtime limits.
ELI5 - Simplified Explanation
Imagine you have a big pile of letter tiles, like the ones used in a board game, and a list of words you want to spell. Each letter tile has a special point value, and the goal is to pick a combination of words that adds up to the highest total score possible.
The code starts by looking at all the letters you have and making a little count of how many of each one is sitting in your pile. After that, it starts a game of choosing. For every word on the list, the code decides to either skip it or try to spell it.
If the code tries to spell a word, it first checks the pile to see if all the letters needed for that word are inside. If the letters are there, it takes them out of the pile, adds up the points for that word, and then moves on to look at the next word with all the remaining letters. If the letters are missing, it simply stops that branch of the search.
By doing this over and over, the code explores every possible way to combine the words using the pile of letter tiles. It keeps track of the total points for each successful combination and remembers which one ended up being the very best. It is just like searching for the path that leads to the biggest treasure chest by trying every turn at a fork in the road.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Python | Java | TS | |||
| WalkCCC | C++ | Python | Java | |||||
| leetcode.ca | C++ | Python | Java | Go | ||||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# |
Videos
Similar Problems
- problem 2151: Maximum Good People Based on Statements
Solved On The Same Day
- problem 859: Buddy Strings
- problem 914: X of a Kind in a Deck of Cards
- problem 925: Long Pressed Name
- problem 1346: Check If N and Its Double Exist
- problem 1805: Number of Different Integers in a String
- problem 1909: Remove One Element to Make the Array Strictly Increasing
- problem 2047: Number of Valid Words in a Sentence
- problem 2469: Convert the Temperature
- problem 2525: Categorize Box According to Criteria
- problem 2591: Distribute Money to Maximum Children
- problem 2614: Prime In Diagonal
- problem 2660: Determine the Winner of a Bowling Game
- problem 2760: Longest Even Odd Subarray With Threshold
- problem 2765: Longest Alternating Subarray
- problem 2251: Number of Flowers in Full Bloom
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality