Problem 1255

Abstract / Summary

Given letters with scores, find the highest total score from words that can be made using the letters.

Note

The full problem description, including helpful examples, can be found on LeetCode.

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)
28 lines | 832 bytes | submitted October 11, 2023 | GitHub   22% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

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
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
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.
LeetCode profile | GitHub repo

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 pos is ignored, and the recursion proceeds with the same available map.
  • 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 of words[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 to gain. After successfully processing the whole word, the recursion continues with the updated have, and the total score for this branch becomes gain + 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 available dictionary 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.

written by openai gpt

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.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.62 | σ = 0.84

Complexity Analysis

Time: exponential
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
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
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#
24 links | 13 authors | 7 languages

Videos

8 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

16 solutions   October 11, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • 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