#1239
Maximum Length of a Concatenated String with Unique Characters
MediumArrayStringBacktrackingBit ManipulationBacktrackingBit Manipulation
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * 2^n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n * 2^n)Space O(1)
We can use backtracking to explore all combinations of strings while maintaining a bitmask to track used characters. This avoids generating unnecessary combinations and checks for uniqueness efficiently.
⚙️
Algorithm
4 steps- 1Step 1: Define a recursive function that takes the current index and the current bitmask of used characters.
- 2Step 2: For each string, check if adding it to the current bitmask maintains uniqueness.
- 3Step 3: If unique, update the maximum length and recurse with the next index.
- 4Step 4: Return the maximum length found.
solution.py18 lines
1# Full working Python code
2def maxLength(arr):
3 def backtrack(index, current_mask):
4 nonlocal max_len
5 max_len = max(max_len, bin(current_mask).count('1'))
6 for i in range(index, len(arr)):
7 new_mask = current_mask
8 for char in arr[i]:
9 new_mask |= (1 << (ord(char) - ord('a')))
10 if new_mask == current_mask + (1 << (ord(arr[i][0]) - ord('a'))):
11 backtrack(i + 1, new_mask)
12
13 max_len = 0
14 backtrack(0, 0)
15 return max_len
16
17# Example usage
18print(maxLength(['un', 'iq', 'ue'])) # Output: 4ℹ
Complexity note: The time complexity is O(n * 2^n) because we explore all subsets of the input array, and each subset can be checked for uniqueness in constant time using bit manipulation.
- 1Using bit manipulation helps efficiently track used characters.
- 2Backtracking allows us to explore combinations without generating all explicitly.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.