Maximum Length of a Concatenated String with Unique Characters (LeetCode 1239): Solution and Explanation
Given an array of strings arr, choose some of them in their original order and concatenate them. The result must not repeat any character. Return the longest possible length of such a concatenation.
Intuition
Order does not actually matter for validity. A concatenation has unique characters exactly when the chosen words have pairwise disjoint letter sets and none of them repeats a letter internally. So the question is really: which group of words has disjoint letter sets and the largest total length?
With only 26 lowercase letters, a letter set fits in one integer. Bit 0 stands for a, bit 1 for b, and so on. Two sets are disjoint exactly when maskA & maskB == 0, and their union is maskA | maskB. That turns every validity check into one AND.
A word that repeats a letter by itself, like aa, can never be part of an answer, so it is dropped immediately when building its mask.
Now build all valid groups incrementally. Start with the empty set. When a new word arrives, every valid group either skips it (already in the list) or includes it, which is only allowed when the group's mask and the word's mask do not overlap. Appending those unions to the list enumerates every valid subsequence exactly once, and the answer is the longest one seen.
Approach: Growing list of letter masks
- Start with
masks = [0]andlens = [0], representing the empty string, andbest = 0. - For each word, build its mask by setting
1 << (ch - 'a')for each character. If a bit is already set, the word repeats a letter, so skip it. - Remember the current size of
masks, then loop over those entries only. - If
masks[i] & m == 0, the word can be glued onto that set. Appendmasks[i] | mandlens[i] + len(word), and updatebest. - After all words, return
best.
Step-by-step example
arr = ["un","iq","ue"]
- Start with the list [""] and best = 0.
- "un" has no repeated letter. The empty set does not overlap it, so append "un" (length 2). best = 2.
- "iq": the empty set gives "iq" (length 2), and "un" shares no letter with it, so append "uniq" (length 4). best = 4.
- "ue": the empty set gives "ue". "un" shares u, so skip. "iq" gives "ique" (length 4). "uniq" shares u, so skip.
- No more words. The list has 6 sets and the longest has length 4, so the answer is 4.
Code: Python, Java, C++
1class Solution:
2 def maxLength(self, arr: List[str]) -> int:
3 masks, lens = [0], [0]
4 best = 0
5 for word in arr:
6 m = 0
7 for ch in word:
8 bit = 1 << (ord(ch) - ord('a'))
9 if m & bit:
10 m = -1
11 break
12 m |= bit
13 if m == -1:
14 continue
15 for i in range(len(masks)):
16 if masks[i] & m == 0:
17 masks.append(masks[i] | m)
18 lens.append(lens[i] + len(word))
19 best = max(best, lens[-1])
20 return best1class Solution {
2 public int maxLength(List<String> arr) {
3 List<Integer> masks = new ArrayList<>();
4 List<Integer> lens = new ArrayList<>();
5 masks.add(0);
6 lens.add(0);
7 int best = 0;
8 for (String word : arr) {
9 int m = 0;
10 for (char ch : word.toCharArray()) {
11 int bit = 1 << (ch - 'a');
12 if ((m & bit) != 0) {
13 m = -1;
14 break;
15 }
16 m |= bit;
17 }
18 if (m == -1) continue;
19 int size = masks.size();
20 for (int i = 0; i < size; i++) {
21 if ((masks.get(i) & m) == 0) {
22 masks.add(masks.get(i) | m);
23 lens.add(lens.get(i) + word.length());
24 best = Math.max(best, lens.get(lens.size() - 1));
25 }
26 }
27 }
28 return best;
29 }
30}1class Solution {
2public:
3 int maxLength(vector<string>& arr) {
4 vector<int> masks = {0};
5 vector<int> lens = {0};
6 int best = 0;
7 for (const string& word : arr) {
8 int m = 0;
9 for (char ch : word) {
10 int bit = 1 << (ch - 'a');
11 if (m & bit) {
12 m = -1;
13 break;
14 }
15 m |= bit;
16 }
17 if (m == -1) continue;
18 int size = masks.size();
19 for (int i = 0; i < size; i++) {
20 if ((masks[i] & m) == 0) {
21 masks.push_back(masks[i] | m);
22 lens.push_back(lens[i] + (int)word.size());
23 best = max(best, lens.back());
24 }
25 }
26 }
27 return best;
28 }
29};Time and space complexity
O(2^n + L)
The list can hold at most one entry per subset of the n words, and each entry costs one AND per later word. Building the masks reads every character once, L in total.
O(2^n)
In the worst case every subset is valid, for example 16 single different letters, and the list holds 2^16 masks.
Other approaches
Backtracking with include or skip (time O(2^n), space O(n))
Recurse over the words with the current mask. At each word, skip it, or include it when it does not overlap the mask. Track the maximum length at the leaves. It explores the same subsets but only stores the recursion path.
Sets of characters instead of bitmasks (time O(26 * 2^n), space O(26 * 2^n))
Use hash sets and check len(a | b) == len(a) + len(b). It is easier to read but each check costs up to 26 operations instead of one AND.
Common mistakes
- Forgetting that a single word can repeat a letter, such as "aa". Its mask would silently drop the duplicate and look valid.
- Looping over the list while appending to it, which in some languages keeps iterating over the new entries and combines the word with itself.
- Assuming the best answer always uses the longest words. A long word can block several shorter words that together are longer.
- Returning the number of sets instead of the longest length.
Frequently asked questions
Why can the order of the subsequence be ignored?
Whether characters repeat depends only on which words are chosen, not on the order in which they are glued together, and the length is the same either way.
Can the list really grow to 2^16 entries?
Yes, when all 16 words use different letters, every subset is valid. That is still only 65,536 integers, which is small.
Why store lengths separately instead of counting bits?
Since a valid set never repeats a letter, its length equals its bit count. Keeping a parallel length list avoids a popcount call, which not every language exposes in the same way.
What does the answer 0 mean?
Every word repeats a letter internally, so nothing can be chosen and the best concatenation is the empty string.