Maximum Length of a Concatenated String with Unique Characters Problem
Description
LeetCode Problem 1239.
You are given an array of strings arr. A string s is formed by the concatenation of a subsequence of arr that has unique characters.
Return the maximum possible length of s.
A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All the valid concatenations are:
- ""
- "un"
- "iq"
- "ue"
- "uniq" ("un" + "iq")
- "ique" ("iq" + "ue")
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible longest valid concatenations are "chaers" ("cha" + "ers") and "acters" ("act" + "ers").
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Explanation: The only string in arr has all 26 characters.
Constraints:
1 <= arr.length <= 161 <= arr[i].length <= 26arr[i]contains only lowercase English letters.
Solution
Approach: Bitmasks of All Valid Concatenations
All characters are lowercase letters, so a string with distinct letters can be stored as a 26-bit mask (bit i set when letter i appears). Two such strings can be concatenated exactly when their masks have no bit in common (a & b == 0), and the result is a | b. The length of a valid concatenation is the number of set bits.
With at most 16 strings there are at most 216 subsequences, so we can build all valid ones:
- Start with the list
masks = [0](the empty concatenation). - For each string, build its mask. If it repeats a letter, skip it: it can never be part of a valid answer.
- Otherwise combine it with every mask already in the list (only the ones from before this string) that has no common letter, add each union to the list, and update the answer with its bit count.
Processing the strings in order and only extending earlier masks keeps every union a subsequence of arr and uses each string at most once. Combinations with repeated letters are never added, so the list stays small in practice.
Complexity: O(2n + L) time and O(2n) space, where n is the number of strings and L their total length.
class Solution:
def maxLength(self, arr: List[str]) -> int:
masks = [0] # letter sets of all valid concatenations so far (bit i = letter i)
ans = 0
for t in arr:
x = 0
for c in t:
bit = 1 << (ord(c) - ord("a"))
if x & bit: # t repeats a letter: it can never be used
x = 0
break
x |= bit
if x == 0:
continue
for i in range(len(masks)): # only the masks from before t
if masks[i] & x == 0:
masks.append(masks[i] | x)
ans = max(ans, bin(masks[i] | x).count("1"))
return ans