Longest Non-Overlapping Character Chain
Math & Bit ManipulationAuto-graded · 20 test casesLast updated
Tests backtracking or bitmask optimization to select a subset of strings whose combined characters are all distinct.
You are given an array of strings words. Your task is to select any subset of these strings and concatenate them together. The goal is to maximize the total length of the concatenated result, under the constraint that no character appears more than once in the final string.
Return the maximum length achievable.
Rules
- You may choose any subset of the input strings, including none at all.
- The order in which you concatenate the chosen strings does not matter for the purpose of counting distinct characters.
- If a string in
wordscontains a repeated character within itself, that string cannot be part of any valid selection. - A character must appear at most once across the entire concatenated result.
Constraints
1 <= words.length <= 161 <= words[i].length <= 26- Each
words[i]consists only of lowercase English letters.
Examples
Example 1
Input: longest_unique_concat(['un', 'iq', 'ue'])
Output: 4
Example 2
Input: longest_unique_concat(['cha', 'r', 'act', 'ers'])
Output: 6
Hints
Hint 1
A string containing duplicate letters within itself can never be used in any valid subset.
Hint 2
Use a bitmask to represent which letters are present in a word or combination—this makes checking for overlaps a single bitwise AND operation.
Hint 3
With at most 16 words, exploring all possible subsets is feasible; use backtracking to avoid generating duplicate combinations.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core challenge is selecting a subset of strings such that their union contains no repeated characters. Two key insights simplify the problem:
-
Eliminate invalid strings immediately. Any string that contains a duplicate letter within itself cannot contribute to a valid solution, so filter these out during preprocessing.
-
Represent each string as a bitmask. Since we only care about which letters are present, encode each valid string as a 26-bit integer where bit
iindicates whether the letter at positioniin the alphabet appears in the string. This allows overlap detection between two strings in constant time using a bitwise AND: ifmask1 & mask2 == 0, the strings share no letters.
With at most 16 input strings, there are at most 2^16 = 65,536 possible subsets, making exhaustive search practical. We use backtracking to explore combinations:
- Start with an empty selection (mask = 0, length = 0).
- At each step, try adding each remaining word whose bitmask does not overlap with the current accumulated mask.
- Track the maximum length encountered across all valid subsets.
- By iterating from the current index forward, we ensure each subset is generated exactly once (as a combination, not a permutation).
The recursion naturally prunes branches where adding a word would introduce a duplicate character.
Why It Works
- Filtering is safe: Any subset containing a self-conflicting word is invalid, so discarding such words loses no optimal solution.
- Backtracking explores every valid combination: Each path from root to leaf in the recursion tree corresponds to one valid subset. The check
current_mask & word_mask == 0ensures only non-overlapping words are added. - Order independence: Since we only care about the set of characters, the order of concatenation is irrelevant. Generating combinations (not permutations) avoids redundant work.
- The empty subset is handled: Starting with
max_len = 0covers the case where no valid selection exists.
Complexity
Time: O(N · L + N · 2^N), where N is the number of words and L is the average word length. Building bitmasks takes O(N · L). The backtracking explores up to 2^N subsets, and at each node we loop through remaining words with O(1) bitmask checks, giving O(N · 2^N) for the search phase. In practice, the search is much smaller because deep paths are constrained by the 26-letter alphabet.
Space: O(N) for storing the valid bitmasks and O(N) for the recursion stack.
from typing import List
def longest_unique_concat(words: List[str]) -> int:
# Preprocess: build bitmasks for words that have no internal duplicates
valid_words = []
for word in words:
char_mask = 0
is_valid = True
for ch in word:
bit_pos = 1 << (ord(ch) - ord('a'))
if char_mask & bit_pos:
is_valid = False
break
char_mask |= bit_pos
if is_valid:
valid_words.append((char_mask, len(word)))
max_len = 0
def explore(idx: int, current_mask: int, current_len: int) -> None:
nonlocal max_len
if current_len > max_len:
max_len = current_len
for i in range(idx, len(valid_words)):
word_mask, word_len = valid_words[i]
if current_mask & word_mask == 0:
explore(i + 1, current_mask | word_mask, current_len + word_len)
explore(0, 0, 0)
return max_len