Maximum Length of a Concatenated String with Unique Characters — LeetCode 1239 Python Solution

MediumBit ManipulationArrayStringBacktracking
Problem
#1239
Reading time
2 min

The problem

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.

Example

Input
arr = ["un","iq","ue"]
Output
4
Explanation
All the valid concatenations are:

Python solution

Python
class Solution:
    def maxLength(self, arr: List[str]) -> int:
        s = [0]
        for t in arr:
            x = 0
            for b in map(lambda c: ord(c) - 97, t):
                if x >> b & 1:
                    x = 0
                    break
                x |= 1 << b
            if x:
                s.extend((x | y) for y in s if (x & y) == 0)
        return max(x.bit_count() for x in s)

Complexity

MeasureComplexity
TimeO(2^n + L)
SpaceO(2^n) auxiliary

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Backtracking.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters?
LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters is rated Medium on LeetCode.
What is the time complexity of LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters?
The Python solution on this page runs in O(2^n + L).
What is the space complexity of LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters?
The Python solution on this page uses O(2^n) auxiliary space.
What topics does LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters cover?
LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters is tagged Bit Manipulation, Array, String and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview