Python 1239.py
class Solution:
def maxLength(self, arr: List[str]) -> int:
# filter words with duplicate characters
words = [ w for w in arr if len(set(w)) == len(w) ]
def deeper(pos, mask):
# processed all words => number of set bits equals the length of string s
if pos == len(words):
return mask.bit_count()
# skip word
best = deeper(pos + 1, mask)
# create bitmask, set bit i if c is the i-th letter in the alphabet
current = 0
for c in words[pos]:
bit = ord(c) - ord("a") # "a" = 0, "b" = 1, ...
current |= 1 << bit
# insert word
if (current & mask) == 0: # ensure there's no overlap
best = max(best, deeper(pos + 1, mask | current))
return best
return deeper(0, 0)
Difficulty
and has an acceptance rate of about 55% (500k+ submissions).
Typical patterns to solve this problem:
- Array
- Backtracking
- Bit Manipulation
- 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 classic “maximum length of a concatenated string with unique characters” problem. It receives a list of strings and returns the greatest possible length of a concatenated string formed by selecting any subset of the input strings such that the resulting string contains no repeated characters. The solution follows a depth-first search (DFS) pattern combined with bit-mask manipulation to represent character sets efficiently.
Core Workflow
The algorithm can be divided into three logical phases: preprocessing, recursive exploration, and result extraction.
Preprocessing - filtering out invalid words
words = [ w for w in arr if len(set(w)) == len(w) ]
During this step each input string is examined to ensure it does not contain duplicate characters internally. By converting the string to a set and comparing its size with the original length, any word that would immediately violate the uniqueness constraint is discarded. This reduces the search space dramatically, especially when the original list contains many repetitive strings.
Recursive Exploration - the deeper function
def deeper(pos, mask):
if pos == len(words):
return mask.bit_count()
best = deeper(pos + 1, mask)
current = 0
for c in words[pos]:
bit = ord(c) - ord("a")
current |= 1 << bit
if (current & mask) == 0:
best = max(best, deeper(pos + 1, mask | current))
return best
The recursion receives two parameters: pos, the index of the word currently under consideration, and mask, a 26-bit integer where each bit indicates whether the corresponding alphabet letter is already present in the concatenated string built so far.
The base case triggers when pos reaches the length of the filtered word list. At that point the number of set bits in mask directly equals the length of the constructed unique-character string, and mask.bit_count() returns this length.
Two branches are explored for each word:
-
Skipping the word - the function recurses with the same
maskand advancespos. This branch guarantees that every subset, including the empty subset, is examined. -
Including the word - before inclusion, the algorithm builds a bitmask
currentfor the word by iterating over its characters and setting the appropriate bits. The condition(current & mask) == 0ensures that the word shares no characters with the already selected set. If the condition holds, the recursion proceeds with an updated mask that merges the new word’s bits (mask | current).
The max operation selects the larger length between the two branches, propagating the optimal result up the call stack.
Result Extraction
return deeper(0, 0)
The initial call starts at position 0 with an empty mask (0). The final integer returned by deeper is the maximum achievable length.
Edge Cases Handled
When the input list is empty, the list comprehension yields an empty words list. The recursive call immediately hits the base case (pos == 0 == len(words)) and returns 0, correctly indicating that no characters can be concatenated.
If every word in the original list contains duplicate characters, the preprocessing step removes all entries, again leading to an empty words list and a result of 0.
Words that consist of a single character are processed without special handling; the bitmask creation loop sets exactly one bit, and the overlap check works identically to longer words.
The algorithm also gracefully handles the situation where a word’s characters are a subset of characters already present in mask. The overlap test (current & mask) == 0 fails, causing the inclusion branch to be skipped while still exploring the skip branch, thereby preserving correctness.
Because the recursion explores all subsets, the case where the optimal solution uses no words (i.e., the empty concatenation) is naturally covered; the skip-only path yields a length of 0.
Performance Optimizations
The most significant optimization is the use of a 26-bit integer to represent character sets. Bitwise operations (|, &) are constant-time and far more efficient than manipulating Python sets or strings during the recursive search.
Pre-filtering words that contain internal duplicates eliminates entire branches of the search tree that could never contribute to a valid solution. This reduction is especially impactful when the input contains many long strings with repeated letters.
The overlap check (current & mask) == 0 acts as a cheap pruning mechanism. If a word shares any character with the current mask, the algorithm avoids the costly recursive call that would inevitably violate the uniqueness constraint.
Utilizing the built-in int.bit_count() method to compute the length of the current concatenation avoids manual counting loops, leveraging a highly optimized native implementation.
Finally, the recursion is tail-light: each call creates only two new frames (skip and possibly include), and the mask is passed by value (an immutable integer), eliminating the need for copying mutable structures. This design keeps the memory footprint low throughout the depth-first traversal.
ELI5 - Simplified Explanation
Imagine you have a big box of word blocks and you want to stack them up to make the longest train possible. However, there is a special rule for this game. You are not allowed to use two of the same letter in your train. For example, if a block has the letter a, you cannot pick another block that also has an a.
First, look at all the words in the pile and throw away any words that already have a repeated letter, because those are broken and cannot be part of the game.
Now, think about starting a path through the pile of remaining words. At each step, a choice must be made. One choice is to simply skip the current word and move on to the next one. The other choice is to try adding the current word to the train, but only if it does not share any letters with the blocks already placed in the train.
This process keeps going step by step until all the words have been looked at. The goal is to keep track of how many letters have been used in the train along the way. Every time a new path is tested, the length is compared to the longest one found so far, always keeping the biggest number. By carefully checking every combination of words that fit together, the final answer represents the longest total count of letters that can be collected in a single train without ever repeating a letter.
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++ | |||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| MemoryLimitExceeded | C++ | Python | ||||||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| chandansgowda | Python | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| vthwang | Java | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++ | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| MemoryLimitExceeded | Python, C++ | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| chandansgowda | Python | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fpdjsns | C++ | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| varunu28 | Java | |||||||
| vthwang | Java | |||||||
| wisdompeak | C++ |
Videos
Solved On The Same Day
- problem 1854: Maximum Population Year
- problem 1869: Longer Contiguous Segments of Ones than Zeros
- problem 1839: Longest Substring Of All Vowels in Order
- problem 1855: Maximum Distance Between a Pair of Values
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