Maximum Length of a Concatenated String with Unique Characters
Maximum Length of a Concatenated String with Unique Characters is a medium recursion & backtracking problem solved with the pick / not-pick pattern.
The best approach, optimal (pick / not-pick with letter bitmasks), runs in O(2^n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from brute force (every subset of strings) up.
Problem
You are given an array of strings arr. Choose any subset of them (possibly none) and concatenate the chosen strings in their original order. The result is valid only if no letter appears more than once in it.
Return the maximum possible length of a valid concatenation.
Examples
Example 1
- Input
arr = ["ab", "cd", "bce", "fg"]- Output
6- Why
- "ab" + "cd" + "fg" = "abcdfg" uses 6 distinct letters. "bce" clashes with both "ab" and "cd".
Example 2
- Input
arr = ["moon", "sun", "sky"]- Output
3- Why
- "moon" repeats the letter o and can never be used; "sun" and "sky" share s, so only one of them fits.
Example 3
- Input
arr = ["pqrstuvwxyz", "abcdefghijklmno"]- Output
26- Why
- The two strings together use every letter exactly once.
Constraints
1 <= arr.length <= 161 <= arr[i].length <= 26arr[i]contains only lowercase English letters.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (3 examples, or your own). Submit also runs 13 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Brute force (every subset of strings) | O(2^n · L) | O(L) |
| Optimal (pick / not-pick with letter bitmasks) | O(2^n) | O(n) |
1Brute force (every subset of strings)
O(2^n · L)2^n subsets, each concatenated and checked in time proportional to its total length L ≤ 26n.O(L)The concatenation for one subset.Enumerate every subset of the strings with a bitmask over indices. For each subset, concatenate its strings and check whether any letter appears twice; if not, its length is a candidate.
- For sub from 0 to 2^n - 1, build the concatenation of every arr[i] whose bit is set.
- Count each letter; if no count exceeds 1, update the best length.
- Return the best length.
class Solution {
public int maxLength(List<String> arr) {
int n = arr.size(), best = 0;
for (int sub = 0; sub < (1 << n); sub++) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++)
if ((sub & (1 << i)) != 0) sb.append(arr.get(i));
int[] cnt = new int[26];
boolean ok = true;
for (int i = 0; i < sb.length() && ok; i++)
if (++cnt[sb.charAt(i) - 'a'] > 1) ok = false;
if (ok) best = Math.max(best, sb.length());
}
return best;
}
}class Solution:
def maxLength(self, arr: List[str]) -> int:
n = len(arr)
best = 0
for sub in range(1 << n):
s = "".join(arr[i] for i in range(n) if sub >> i & 1)
if len(set(s)) == len(s):
best = max(best, len(s))
return bestclass Solution {
public:
int maxLength(vector<string>& arr) {
int n = arr.size(), best = 0;
for (int sub = 0; sub < (1 << n); sub++) {
string s;
for (int i = 0; i < n; i++)
if (sub & (1 << i)) s += arr[i];
int cnt[26] = {0};
bool ok = true;
for (char c : s)
if (++cnt[c - 'a'] > 1) { ok = false; break; }
if (ok) best = max(best, (int)s.size());
}
return best;
}
};function maxLength(arr) {
const n = arr.length;
let best = 0;
for (let sub = 0; sub < (1 << n); sub++) {
let s = "";
for (let i = 0; i < n; i++)
if (sub & (1 << i)) s += arr[i];
if (new Set(s).size === s.length) best = Math.max(best, s.length);
}
return best;
}2Optimal (pick / not-pick with letter bitmasks)
O(2^n)At most 2^n recursion leaves, each step O(1) with bit operations, and clashes prune many branches.O(n)The masks and the recursion depth.Turn each string into a 26-bit mask of its letters and throw away strings that repeat a letter on their own. Then recurse over the remaining masks: at index i you either skip it or, if it shares no bit with the letters used so far, take it. Clashing branches are cut immediately, and every check is a single AND.
- For each string, build its mask; keep it only if its bit count equals its length.
- dfs(i, used): if i == number of masks, return bitCount(used).
- best = dfs(i + 1, used); if (masks[i] & used) == 0, best = max(best, dfs(i + 1, used | masks[i])).
- Return dfs(0, 0).
class Solution {
private int[] masks;
private int m;
public int maxLength(List<String> arr) {
masks = new int[arr.size()];
m = 0;
for (String s : arr) {
int mask = 0;
for (char c : s.toCharArray()) mask |= 1 << (c - 'a');
if (Integer.bitCount(mask) == s.length()) masks[m++] = mask;
}
return dfs(0, 0);
}
private int dfs(int i, int used) {
if (i == m) return Integer.bitCount(used);
int best = dfs(i + 1, used);
if ((masks[i] & used) == 0) best = Math.max(best, dfs(i + 1, used | masks[i]));
return best;
}
}class Solution:
def maxLength(self, arr: List[str]) -> int:
masks = []
for s in arr:
mask = 0
for c in s:
mask |= 1 << (ord(c) - 97)
if bin(mask).count("1") == len(s):
masks.append(mask)
m = len(masks)
def dfs(i: int, used: int) -> int:
if i == m:
return bin(used).count("1")
best = dfs(i + 1, used)
if masks[i] & used == 0:
best = max(best, dfs(i + 1, used | masks[i]))
return best
return dfs(0, 0)class Solution {
vector<int> masks;
int dfs(int i, int used) {
if (i == (int)masks.size()) return __builtin_popcount(used);
int best = dfs(i + 1, used);
if ((masks[i] & used) == 0) best = max(best, dfs(i + 1, used | masks[i]));
return best;
}
public:
int maxLength(vector<string>& arr) {
masks.clear();
for (const string& s : arr) {
int mask = 0;
for (char c : s) mask |= 1 << (c - 'a');
if (__builtin_popcount(mask) == (int)s.size()) masks.push_back(mask);
}
return dfs(0, 0);
}
};function maxLength(arr) {
const bits = (x) => {
let c = 0;
while (x) {
x &= x - 1;
c++;
}
return c;
};
const masks = [];
for (const s of arr) {
let mask = 0;
for (const ch of s) mask |= 1 << (ch.charCodeAt(0) - 97);
if (bits(mask) === s.length) masks.push(mask);
}
const dfs = (i, used) => {
if (i === masks.length) return bits(used);
let best = dfs(i + 1, used);
if ((masks[i] & used) === 0) best = Math.max(best, dfs(i + 1, used | masks[i]));
return best;
};
return dfs(0, 0);
}Edge cases to test
- A string that repeats a letter by itself (it can never be chosen)
- Every string clashes with every other one
- All strings together are unique (take all of them)
- Picking a long string early blocks a better combination of shorter ones
Hints
Hint 1
Each string is either taken or not, and there are at most 2^16 combinations.
Hint 2
Represent a set of letters as a 26-bit mask. Two strings clash exactly when their masks share a bit.
Hint 3
Drop strings that repeat a letter on their own, then do pick / not-pick recursion carrying the mask of letters used so far.
FAQ
What is the best time complexity for Maximum Length of a Concatenated String with Unique Characters?
Optimal (pick / not-pick with letter bitmasks) runs in O(2^n) time and O(n) extra space. At most 2^n recursion leaves, each step O(1) with bit operations, and clashes prune many branches.
Which pattern does Maximum Length of a Concatenated String with Unique Characters use?
It is a recursion & backtracking problem that uses the pick / not-pick pattern. Other problems with the same pattern: Generate all binary strings without consecutive 1's, Subsets (2 choices per element), Subsets II.
Is there a brute force solution for Maximum Length of a Concatenated String with Unique Characters?
Yes. Brute force (every subset of strings) takes O(2^n · L) time and O(L) space. Enumerate every subset of the strings with a bitmask over indices.
Which edge cases should I test for Maximum Length of a Concatenated String with Unique Characters?
A string that repeats a letter by itself (it can never be chosen); Every string clashes with every other one; All strings together are unique (take all of them); Picking a long string early blocks a better combination of shorter ones.