Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find length of concatenated string of unique characters in Python?
Given a list of strings, we need to find the maximum length of a concatenated string formed by selecting a subsequence of words where each character appears only once in the final string.
The problem requires us to explore all possible combinations of words and find the one with maximum length that contains only unique characters.
Algorithm Approach
We use a recursive backtracking approach:
- For each word, we have two choices: include it or exclude it
- We can only include a word if it has unique characters and doesn't create duplicates when combined with our current string
- We track the maximum length found so far
Example
Let's implement the solution with a helper function to check unique characters ?
class Solution:
def solve(self, words):
ans = 0
def is_all_unique(s):
return len(set(s)) == len(s)
def recur(i=0, cur=""):
nonlocal ans
if i == len(words):
ans = max(ans, len(cur))
return
# Option 1: Skip current word
recur(i + 1, cur)
# Option 2: Include current word if valid
if is_all_unique(words[i]) and is_all_unique(cur + words[i]):
recur(i + 1, cur + words[i])
recur()
return ans
# Test the solution
ob = Solution()
words = ["xyz", "xyw", "wab", "cde"]
result = ob.solve(words)
print(f"Maximum length: {result}")
Maximum length: 9
How It Works
Let's trace through the example with words = ["xyz", "xyw", "wab", "cde"]:
words = ["xyz", "xyw", "wab", "cde"]
# Check each word for unique characters
for word in words:
unique_chars = len(set(word)) == len(word)
print(f"'{word}': unique characters = {unique_chars}")
# Best combination would be "xyz" + "wab" + "cde" = "xyzwabcde" (length 9)
best_combo = "xyz" + "wab" + "cde"
print(f"\nBest combination: '{best_combo}'")
print(f"Length: {len(best_combo)}")
print(f"All unique: {len(set(best_combo)) == len(best_combo)}")
'xyz': unique characters = True 'xyw': unique characters = True 'wab': unique characters = True 'cde': unique characters = True Best combination: 'xyzwabcde' Length: 9 All unique: True
Alternative Implementation
Here's a cleaner version using sets for character tracking ?
def max_unique_concat_length(words):
def backtrack(index, current_chars):
if index == len(words):
return len(current_chars)
# Skip current word
max_len = backtrack(index + 1, current_chars)
# Try including current word
word_chars = set(words[index])
if len(word_chars) == len(words[index]) and not word_chars & current_chars:
max_len = max(max_len, backtrack(index + 1, current_chars | word_chars))
return max_len
return backtrack(0, set())
# Test with different examples
test_cases = [
["xyz", "xyw", "wab", "cde"],
["ab", "cd", "ef"],
["abc", "def", "ghi"]
]
for i, words in enumerate(test_cases):
result = max_unique_concat_length(words)
print(f"Test case {i+1}: {words}")
print(f"Maximum length: {result}\n")
Test case 1: ['xyz', 'xyw', 'wab', 'cde'] Maximum length: 9 Test case 2: ['ab', 'cd', 'ef'] Maximum length: 6 Test case 3: ['abc', 'def', 'ghi'] Maximum length: 9
Key Points
- The algorithm uses backtracking to explore all possible combinations
- We check for unique characters within each word and across the concatenated string
- Time complexity: O(2^n) where n is the number of words
- Space complexity: O(n) for recursion stack
Conclusion
This backtracking approach systematically explores all valid combinations of words to find the maximum length concatenated string with unique characters. The key insight is using recursion with two choices per word: include or exclude.
