Magicsheet logo

Maximum Length of a Concatenated String with Unique Characters

Medium
64.9%
Updated 6/1/2025

Maximum Length of a Concatenated String with Unique Characters

What is this problem about?

The Maximum Length of a Concatenated String with Unique Characters coding problem gives you an array of strings. You want to find the length of the longest possible string formed by concatenating a subsequence of these strings such that every character in the result appears exactly once. Characters must be unique across the entire concatenated result, not just within each string.

Why is this asked in interviews?

Companies like Microsoft, Meta, Google, Palo Alto Networks, and Adobe include this problem because it cleanly combines backtracking with bit manipulation optimization. The naive backtracking explores 2^n subsets; the bitmask optimization reduces character set membership checks to O(1) bitwise operations. This problem tests both algorithmic design and implementation efficiency.

Algorithmic pattern used

The solution uses backtracking with bitmask. Represent each string's character set as a 26-bit integer. Pre-filter strings with duplicate characters (their bitmask would have a bit set more than once, detectable by checking if the count of set bits equals the string length). Then backtrack: at each step, either skip the current string or include it (if its bitmask doesn't overlap with the current accumulated bitmask). Track the maximum length seen.

Alternatively, maintain a list of valid (bitmask, length) pairs achieved so far and iterate over all strings, extending each pair if the new string is compatible.

Example explanation

Strings: ["ab", "cd", "abc"]

  • "ab" → mask = 0b11, len=2. Valid (no duplicates).
  • "cd" → mask = 0b1100, len=2. Valid.
  • "abc" → mask = 0b111, len=3. Valid.

Concatenations:

  • "ab" + "cd" = "abcd": masks have no overlap (0b11 & 0b1100 = 0). Length = 4.
  • "ab" + "abc": 0b11 & 0b111 ≠ 0. Overlap (shared 'a', 'b'). Invalid.
  • "cd" + "abc" = "cdabc": 0b1100 & 0b111 = 0b100 ≠ 0. Overlap ('c'). Invalid.
  • Best = "abcd", length = 4.

Common mistakes candidates make

  • Including strings with internal duplicates: A string like "aab" can never be part of a valid concatenation. Filter these out early.
  • Using string concatenation for overlap check: O(n) string operations instead of O(1) bitwise AND wastes time.
  • Not considering the empty concatenation: The base case (empty string, length 0) must be included for correctness.

Interview preparation tip

For the Array Backtracking String Bit Manipulation interview pattern, always represent character sets as 26-bit integers in string uniqueness problems. The two operations you need — check overlap (mask1 & mask2 != 0) and combine (mask1 | mask2) — are both O(1). This pattern appears in many "unique character" string problems across top company interviews.

Similar Questions